如何在特定的时间间隔内逐行连续地使用python打印文件



我有一个4个网站名称的文件,如下所示。我想在特定的时间间隔内,逐个连续打印每个网站的名称。

sample.txt:

facebook.com
gmail.com
test.com
yahoo.com

我已经尝试了以下代码。但它的印刷版网站只命名一次。我想不停地找名字

from time import sleep
while True:
    with open ("sample.txt", 'r') as test:
        while True:
            print test.readline()
            sleep(3)
    pass
预期输出:

facebook.com
gmail.com
test.com
yahoo.com
facebook.com
gmail.com
test.com
yahoo.com
facebook.com
gmail.com
test.com
yahoo.com
facebook.com
gmail.com
test.com
yahoo.com
.
.
.   

我可以得到帮助来解决这个问题吗?

谢谢。

问题是,在readline()到达文件末尾后,它将继续返回空行。你需要一些结束循环的东西,这样你就可以从文件的开头重新开始:

from time import sleep
while True:
    with open ("sample.txt", 'r') as test:
        for line in test:
            print line.rstrip()
            sleep(3)

如果您真的想使用readline,那么您需要测试文件的结尾。当readline读取实际行时,它将始终至少返回一个换行符。如果它不返回任何内容,那么它就到达了文件的末尾。因此:

from time import sleep
while True:
    with open ("sample.txt", 'r') as test:
        while True:
            line = test.readline()
            if not line:
                break
            print line.rstrip()
            sleep(3)

返回迭代器的文件对象在第一轮调用readline()后耗尽。相反,您应该将整个文件读入一个列表,并依次遍历该列表。

from time import sleep

with open ("sample.txt") as test:
    lines = test.readlines() # read all lines into list
while True:
    for line in lines:
        print line
        sleep(3)

你只需要在每行上循环:

for line in test:
    print line

代替while True:

完成:

from time import sleep
with open ("sample.txt", 'r') as test:
    for line in test
        print line
        sleep(3)

最新更新