#1.读取文件磁盘的内容 file = open('1.txt','r') print(file.read()) #从头读到尾 print(file.readline()) #读取一行 print(file.readlines()) #将文本每一行作为一个独立的字符串,放入列表 file.close() #2.常用的文件打开形式 file = open('2.txt','w') #替换文件内容 file.write('hello wangyuan') file = open('2.txt','a') #对文件内容进行追加 file.write('hello wangyuan') lst = ['java','go','python'] file.writelines(lst) #写入列表的内容 file.seek(2) #对字符进行跳过,跳过两个字符位 file.close() src_file = open('cat.jpg','rb') #以二进制方式进行读取 target_file = open('cat2.jpg','wb') target_file.write(src_file.read()) #复制图片完成读写操作 target_file.close() src_file.close() #3.with 上下文管理器 with open('1.txt','r') as ffile: print(ffile.read()) #4.os模块,与操作系统相关的文件 import os os.system('notepad.exe') #与windos+r效果相同,打开记事本 os.system('calc.exe') #打开计算器 os.startfile(r'"C:\Program Files (x86)\Tencent\QQ\Bin\QQScLauncher.exe"') #执行可执行文件 os.path.join(r'D:\pythonProject','1.txt') #对对应路径进行拼接
2023.4.12 python学习记录(操作文件内容以及os模块)
于 2023-04-12 20:31:41 首次发布