[英]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 我希望程序一个接一个地打印.txt中的行
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. PS您不需要在开放的rt,因为t模式是默认的。
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. f是文件对象,不能对其进行迭代,但是可以对f.readlines进行迭代,该f.readlines将文件中的行列表作为文本返回。
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: “我希望程序以最简单的形式依次打印.txt中的行”对应于:
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.
那里的.strip命令可以删除任何换行符,这些换行符会在行之间产生一个空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.