第二次迭代文件不起作用 [英] Iterating on a file doesn't work the second time

查看:26
本文介绍了第二次迭代文件不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在迭代文件时遇到问题.这是我在解释器上输入的内容和结果:

<预><代码>>>>f = open('baby1990.html', 'rU')>>>对于 f.readlines() 中的行:... 打印(行)...# ... 文件中的所有行都出现在这里 ...

当我再次尝试迭代同一个打开的文件时,我什么也没得到!

<预><代码>>>>对于 f.readlines() 中的行:... 打印(行)...>>>

根本没有输出.为了解决这个问题,我必须 close() 文件然后再次打开它进行阅读!这是正常行为吗?

解决方案

是的,这是正常行为.你基本上是第一次读到文件的末尾(你可以把它想象成读磁带),所以除非你重置它,否则你不能再读它,要么使用 f.seek(0) 重新定位到文件的开头,或者关闭它然后再次打开它,这将从文件的开头开始.

如果您愿意,可以改用 with 语法,它会自动为您关闭文件.

例如

 with open('baby1990.html', 'rU') as f:对于 f 中的行:印刷线

一旦此块执行完毕,文件将自动为您关闭,因此您可以重复执行此块,而无需自己明确关闭文件并再次以这种方式读取文件.

I have a problem with iterating on a file. Here's what I type on the interpreter and the result:

>>> f = open('baby1990.html', 'rU')
>>> for line in f.readlines():
...  print(line)
... 
# ... all the lines from the file appear here ...

When I try to iterate on the same open file again I get nothing!

>>> for line in f.readlines():
...  print(line)
... 
>>>

There is no output at all. To solve this I have to close() the file then open it again for reading! Is that normal behavior?

解决方案

Yes, that is normal behavior. You basically read to the end of the file the first time (you can sort of picture it as reading a tape), so you can't read any more from it unless you reset it, by either using f.seek(0) to reposition to the start of the file, or to close it and then open it again which will start from the beginning of the file.

If you prefer you can use the with syntax instead which will automatically close the file for you.

e.g.,

with open('baby1990.html', 'rU') as f:
  for line in f:
     print line

once this block is finished executing, the file is automatically closed for you, so you could execute this block repeatedly without explicitly closing the file yourself and read the file this way over again.

这篇关于第二次迭代文件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆