编写一个程序 能够读取不断更新的文件,代码示例:
import os
import time
#只读方式打开123.txt
file = open('./123.txt', 'r')
size = os.path.getsize('./123.txt')
print('size=', size)
#获取文件当前位置
now_pos = file.tell()
print('pos=', file.tell())
while 1:
if (now_pos < size):
#读取全部行
lines = file.readlines()
for line in lines:
print(line)
elif (now_pos == size):
time.sleep(0.1)
else:
#如果文件被删除,默认是新的文件重头开始
file.seek(0, 0)
now_pos = file.tell()
size = os.path.getsize('./123.txt')
now_pos = file.tell()
file.seek(now_pos, 0)