文件操作(二)
上一章涉及的r、w、a称为纯净模式
一、r+、w+、a+
with open (r'test',mode = 'r+',encoding = 'utf-8')as f:
print(f.readable())
print(f.writable())
print(f.readline())
f.write('嘻嘻嘻')
with open (r'test',mode = 'w+',encoding = 'utf-8')as f:
print(f.readable())
print(f.writable())
print(f.readline())
f.writr('嘿嘿嘿')
with open (r'test',mode = 'r+b',encoding = 'utf-8')as f:
print(f.readable())
print(f.writable())
res = f.read()
print(res.decode('utf-8'))或print(str(res,encoding = 'utf-8'))
二、文件内光标的移动
f.seek(offset.whence)
offset:相对偏移量(光标移动的位数)
whence:0:参考文件的开头 t和b模式都可以使用
1:参考光标所在的位置 只能在b模式使用
2:参考文件末尾 只能在b模式使用
with open (r'test','r',encoding = 'utf-8')as f:
print(f.read(1))
f.seek(6,0) #seek移动的都是字节数
print(f.read(1)) #在光标后再读取一个字节
with open(r'test','rb') as f:
print(f.read(3).decode('utf-8'))
print(f.seek(3,1)) #在当前光标位置往后移三个字节
with open(r'test','rb') as f:
f.seek(-6, 2)
print(f.read(3).decode('utf-8'))
with open (r'test','r+',encoding='utf-8')as f:
f.seek(3,0)
f.write('过')#只能覆盖,不能增加
三、写日志
四、检测文件内容
with open (r'text.txt','rb')as f:
f.seek(0,2)
while True:
res = f.readline()
if res:
print('新增内容为:%s'.decode('uf-8'))
else:
print('暂无新内容')
五、截断文件
with open(r'test','a',encoding='utf-8') as f:
f.truncate(6)
六、修改文件
方法一:
with open(r'test.txt','r',encoding='utf-8')as read_f: data = read_f.read() with open(r'test.txt','w',encoding = 'utf-8')as write_f: res = data.replace('yzy','sb') write_f.write(res)
优点:任意时间硬盘里都只有一个文件,不会过多占用硬盘空间
缺点:当文件过大的情况下,可能会造成内存溢出
方法二:
import os with open (r'test.txt','r',encoding='utf-8')as read_f,\ open(r'test.swap','a',encoding='utf-8')as write_f: for line in read_f: new_line = line.replace('sb','yzy') write_f.write(new_line) os.remove('test.txt') os.rename('test.swap','test.txt')
优点:内存中始终只有一行内容,不占内存
缺点:在某一时刻硬盘上会同时存在两个文件