使用Python迭代文件 [英] Iterating on a file using Python

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

问题描述

我有一个问题要理解迭代文件,在这里我继续我在解释器上输入的内容和结果:

I have a problem to understand iterating on a file, Here I go on 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 got nothing!!!!

>>> f = open('baby1990.html', 'rU')
>>> for line in f.readlines():
>>>    print(line)
>>>
>>>

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

There is no output at all, to solve this I've to close() the file then open it again for reading!! Is that a 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.

如果您愿意,可以使用语法代替,这将自动为您关闭文件。

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.

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

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