简体   繁体   中英

Printing a line after another from a text file in loop with delay

I want the program to print the lines in the .txt one after another

import os
import time
with open('e.txt','rt') as f:

    #for line  in f:  # for direct input
    line = f.readline()
    m =  str(line)
    print 'd', m
    time.sleep(2)

    line = f.readline()
    g = str(line)
    print 'f', g

As you see there are two lines so printing them this way works fine, but when i want to use a loop

 with open('e.txt','rt') as f:
    for i, l in enumerate(f):
                pass
        d = i + 1
        while d > 0 :
            #with open('e.txt','rt') as f:
            pos = f.tell();
            f.seek(pos,0);
            line=f.readline();
            m = str(line);
            time.sleep(1)
            print 't: ', m
            d -= 1

the output is

t:

t:

i dont understand what am i doing wrong please help

also thanks in advance.

It seems like you are overdoing it, you can do it pretty simply like so:

import time
f = open('e.txt','r')
for line in f.readlines():
    print(line)
    time.sleep(1)

That's it....

PS you dont need rt in the open as the t mode is default.

EDIT: the problem with your program is that you were trying to print an object because when you write

f = open(...) 

or

with open(...) as f

f is a file object, you cant iterate over it, you can however iterate over f.readlines which returns a list of the lines in the file as text.

open the file, iterate the file object.

file = open( 'e.txt', 'r')
for line in file:
    print(line)

"i want the program to print the lines in the .txt one after another" in its simplest form corresponds to:

with open('e.txt','r') as f:
     for line in f:
        print(line.strip())

A delay is a matter of choice, not a necessity to solve the original request. The .strip command is there to remove any newline characters which will produce a space between your lines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM