我正在尝试使用txt文件中的python计时器按特定间隔读取每一行
但是它只读取第一行,并且连续显示
我的代码是
def read():
try:
while True:
fo = open("foo.txt", "r")
threading.Timer(1.0, read).start()
line=fo.readline()
print line
if len(line)==0:
break
except:
pass
read()
最佳答案
问题是您再次打开文件,该文件从第一行开始读取,并在读取该行后打印该文件,然后再次继续循环,这使循环成为无限循环。
另外,您对threading.Timer()
的使用方式也不是您的用法,threading.Timer()
在1秒钟后在新线程中启动read
函数,一段时间后,您将有很多线程无限期地运行read()
函数。
您可以通过使用threading.Timer()
轻松地完成您想要做的事情(无需使用time.sleep()
),以使程序休眠特定的秒数。例子 -
def read():
import time
with open("foo.txt", "r") as fo:
for line in fo:
print line
time.sleep(1)
read()
如果您确实要使用
threading.Timer()
,则不需要while
循环,您应该将文件对象作为参数传递给函数,例如-def read(fo):
line=fo.readline()
print line
if len(line) == 0:
return
t = threading.Timer(1.0, read, args=(fo,))
t.start()
t.join()
然后最初将函数调用为-
with open("foo.txt", "r") as fo:
read(fo)
示例/演示-
>>> def a(x):
... if x >50:
... return
... print(x)
... t = threading.Timer(1.0 , a, args=(x+1,))
... t.start()
... t.join()
...
>>> import threading
>>> a(1)
1
2
3
4
5
6
7
8
关于python - 使用计时器逐行读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31890061/