控制文件内指针移动——打day10

强调:只有t模式下read(n),n代表字符个数,除此以外都是以字节为单位
  with open('a.txt',mode='rt',encoding='utf-8')as f:
  res=f.read(4)#打印后面的字符
  print(res)
  结果:你好啊h

with open('a.txt',mode='rb')as f:
res=f.read(3)
peint(res.decode('utf-8))
结果:你

with open('a.txt',mode='at',encoding='utf-8') as f:
f.truncate(3)
只保留 truncate (3)之前的数据,之后的都删除掉,只能以字符控制

f.seek():指针移动是以字节为单位的
三种模式:
只有0模式既可以在t下用也可以在b下用,而1、2两种模式只能在b模式下使用
0(默认的):参照文件开头
with open('a.txt',mode='rt',encoding='utf-8')as f:
f.seek(3,0)
print(f.tell())#查看文件指针当前所在的位置
print(f.read())
结果:

3
好啊hello

1: 参照指针当前所在位置
with open('a.txt',mode='rb') as f:
f.read(2)
f.seek(4,1)
print(f.tell())#查看文件指针当前所在的位置
print(f.read().decode('utf-8'))
结果:

6
啊hello

2: 参照文件末尾
with open('a.txt',mode='rb') as f:
f.seek(-5,2)
print(f.tell())#查看文件指针当前所在的位置
print(f.read().decode('utf-8'))
结果:

9
hello


后台监视小程序
import time#调用时间模块

with open('access.log',mode='rb') as f:
f.seek(0,2)#跳到文件末尾
while True:
line=f.readline()#每次读取一行
if len(line) == 0:#如果line的长度为0的话
time.sleep(0.1)#停0.1秒
else:
print(line.decode('utf-8'),end='')#否者把他的内容打印出来

 

posted @ 2018-11-27 14:27  WenChen-0o0  阅读(156)  评论(0编辑  收藏  举报