rcubefather rcubefather - 2 months ago 8
Python Question

How to print a file line by line in specific interval continuously using python?

I have a file with 4 website names as shown below. I want to print each website name one by one continuously, in specific interval.

sample.txt:

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


I have tried with following code. But its print website names only once. I wanted to website names continuously.

from time import sleep

while True:
with open ("sample.txt", 'r') as test:
while True:
print test.readline()
sleep(3)
pass


Expected output:

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
.
.
.


Can I get help to fix this issue?

Thanks.

Answer

The problem is that, after readline() reaches the end of the file, it will continue to return empty lines. You need something that ends the loop so that you can start over on the beginning of the file:

from time import sleep

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

If you really want to use readline, then you need to test for the end of file. While readline is reading actual lines, it will always return at least a newline character. If it returns nothing, then it has reached the end of the file. Thus:

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)