控制文件内指针移动

一、f.seek(字节个数,模式)
模式有三种
0:参照文件的开头
1:参照当前所在的位置
2:参照文件末尾的位置

# 注意:
# 1、无论何种模式,都是以字节单位移动,只有t模式下的read(n)的n代表的是字符个数
with open('a.txt',mode='rt',encoding='utf-8') as f:
data=f.read(6)
print(data)

with open('a.txt',mode='rb') as f:
data=f.read(6)
print(data.decode('utf-8'))

# 2、只有0模式可以在t模式下使用,而0、1、2都可以在b模式下用

# 示例
with open('a.txt',mode='rb') as f:
f.seek(6,0)
print(f.read().decode('utf-8'))
f.seek(16,1)
print(f.tell())

f.seek(-3,2)
print(f.read().decode('utf-8'))

f.seek(0,2)
print(f.tell())



with open('b.txt',mode='wt',encoding='utf-8') as f:
f.seek(10,0)
print(f.tell())

f.write("你好")


# 应用1:tail -f access.log
import time

with open('access.log',mode='rb') as f:
f.seek(0,2)

while True:
line=f.readline()
if len(line) == 0:
time.sleep(0.3)
else:
print(line.decode('utf-8'),end='')


原文地址:https://www.cnblogs.com/datatool/p/13457462.html