Reputation: 25
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.
Upvotes: 0
Views: 269
Reputation: 1063
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....
P.S. 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.
Upvotes: 1
Reputation: 706
"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.
Upvotes: 0
Reputation: 26667
open the file, iterate the file object.
file = open( 'e.txt', 'r')
for line in file:
print(line)
Upvotes: 0