我有一个文本文件,每隔10秒由另一个程序写入。 我的代码遍历此文件并解析我想要的数据。但在某些时候,for循环到达文件末尾并且程序关闭。
目标:我希望程序在for循环内等待更多数据,以便它也解析新数据。
我尝试使用一段时间,条件是关于要读取的行,但由于某种原因,程序只是在退出while循环后停止一点。如果我添加让我们说25行...它处理9他们然后程序退出for循环和程序完成(而不是崩溃)
问题:在新数据到货之前,是否有更好的方法可以使程序空闲?这段代码有什么问题?
k = -1
with open('epideiksh.txt') as weather_file:
for line in weather_file:
k = k+1
lines_left = count_lines_of('epideiksh.txt') - k
while ( lines_left <= 10 ):
print("waiting for more data")
time.sleep(10)
pointer = count_lines('epideiksh.txt') - k
if line.startswith('Heat Index'):
do_my_thing()
time.sleep(10)
答案 0 :(得分:0)
模拟tail
的最简单但容易出错的方法是:
with open("filename") as input:
while True:
for line in input:
if interesting(line):
do_something_with(line)
sleep a_little
input.seek(0, io.SEEK_CUR)
在我非常有限的测试中,这似乎没有寻求工作。但它不应该,因为通常你必须做那样的事情,以清除eof标志。要记住的一件事是,在迭代时,不能在(文本)文件上使用tell(),并且从SEEK_CUR中搜索会调用tell()。因此,在上面的代码段中,您无法break
循环for
循环并进入input.seek()
调用。
上面的问题是readline
(迭代器中隐含的)可能只读取当前正在写入的行的一部分。所以你需要准备放弃并重读部分线:
with open("filename") as input:
# where is the end of the last complete line read
where = input.tell()
# use readline explicitly because next() and tell() are incompatible
while True:
line = input.readline()
if not line or line[-1] != '\n':
time.sleep(a_little)
input.seek(where)
else:
where = input.tell()
if interesting(line):
do_something_with(line)