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

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

问题描述

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

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)
... 
>>>

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

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?

推荐答案

是的,这是正常行为.基本上,您是第一次读取文件的末尾(可以像读取磁带一样将其显示为图片),因此除非您使用f.seek(0)来重新定位到文件的位置,否则除非从头读取文件,否则您将无法再读取文件的末尾.文件的开头,或者将其关闭然后再次打开,它将从文件的开头开始.

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.

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

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

例如

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天全站免登陆