[英]Readline() in a loop is not working in python
I have a file called file
with this text: 我有一个名为
file
,其内容为:
Hello
I am not a bot
I am a human
Do you believe me?
I know you won't
Yes I am a bot
Yes you thought it right
This code prints out all the lines of the text: 此代码打印出文本的所有行:
with open(file) as f:
for i in f:
print(i,end="")
But this code does not, and I don't understand why. 但是这段代码没有,我也不明白为什么。
with open(file) as f:
for i in f:
print(f.readline(),end="")
This prints out: 打印输出:
I am not a bot
Do you believe me?
Yes I am a bot
What I understand is as the loop goes over the lines in the file, it will read that line and return that as a string which is then printed. 我的理解是作为循环越过文件中的行,它会读取该行并返回一个字符串,然后打印出来。 If I replace the for loop with
for i in range(9)
, it works. 如果我用
for i in range(9)
的for替换for循环,则可以正常工作。
文件对象上的for循环隐式地调用readline
(或等效方法),因此发生的是,在每个循环中,您两次调用readline
,这就是为什么每隔一行获取一次的原因
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.