文件内光标的移动
一:光标的移动
with open(r'b.txt', 'rb') as f:
print(f.read(4).decode('utf8'))
print(f.tell()) # 查看光标移动了多少个字节
f.seek(3, 1)
print(f.read().decode('utf8'))
控制文件内光标的移动 f.seek()
f.seek(offset,whence)
offset表示位移量
始终是以字节为最小单位
正数从左往右移动
负数从右往左移动
whence表示模式
0:以文件开头为参考系(支持tb两种模式)
1:值支持b模式 以当前位置为参考系
2:只支持b模式 以文件末尾为参考系
import time
with open('a.txt', 'rb') as f:
f.seek(0, 2)
while True:
line = f.readline()
if len(line) == 0:
# 没有内容
time.sleep(0.5)
else:
print(line.decode('utf-8'), end'')
二:文件的内容修改
文件的内容修改方式1 覆盖
with open(r'c.txt', 'r', encoding= 'utf8') as f:
data = f.read()
print(type(data))
with open(r'c.txt', 'w', encoding='utf8') as f1:
new_data = data.replace('tony', 'jason')
f1.write(new_data)
方式2 新建
import os
with open('c.txt', mode='rt', encoding='utf-8') as read_f,
open('c.txt.swap', mode='wt', encoding='utf-8') as write_f:
vfor line in read_f:
write_f.write(line.replace('SB', 'kevin'))
os.remove('c.txt') # 删除原文件
os.rename('c.txt.swap', 'c.txt') # 重命名文件
自己总结两种方式的优缺点