python 日记 day8 文件操作
文件操作:
1.文件路径
2.编码方式 :utf-8 ,gbk .........................
3.操作方式 :只读,只写,追加,读写,写读........................
只读: 绝对文件: f = open('D:\zbiji123\python自学.txt',mode = 'r',encoding = 'utf-8') print(f.read(10)) read 是按字符来读 相对文件; f = open('day-2\zuoye.py',mode = 'r',encoding = 'utf-8') print(f.read())
byte 类型
f = open('day-2\zuoye.py',mode = 'rb')
print(f.read())
只写:
type 类型: f = open('day-2\zuoye.py',mode = 'wb') f.write('aaaaaaaaaaaaa'.encode('utf-8')) f.close() f = open('day-2\zuoye.py',mode = 'w',encoding='utf-8') f.write('aaaaaaaaaaaaa') f.close()
追加: f = open('day-2\zuoye.py',mode = 'a',encoding='utf-8') f.write('aaaaaaaaaaaaa') f.close()
读写: f = open('day-2\zuoye.py',mode = 'r+',encoding='utf-8') content = f.read() print(content) f.write('ccc') f.close() type 类型 f = open('day-2\zuoye.py',mode = 'r+b') content = f.read() print(content) f.write('ccc'.encode('utf-8')) f.close()