python中的文件对象是否可迭代 [英] Is file object in python an iterable

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

问题描述

我有一个文件"test.txt":

I have a file "test.txt":

this is 1st line
this is 2nd line
this is 3rd line

以下代码

lines = open("test.txt", 'r')
for line in lines:
    print "loop 1:"+line
for line in lines:
    print "loop 2:"+line

仅打印:

loop 1:this is 1st line

loop 1:this is 2nd line

loop 1:this is 3rd line

它根本不打印出loop2.

It doesn't print loop2 at all.

两个问题:

  1. open()返回的文件对象,它是可迭代的吗?这就是为什么可以在for循环中使用它的原因?

  1. the file object returned by open(), is it an iterable? that's why it can be used in a for loop?

为什么根本不打印出loop2?

why loop2 doesn't get printed at all?

推荐答案

它不仅是 iterable ,而且是 iterator ,这就是为什么它只能遍历的原因文件一次.您可以按照许多建议使用.seek(0)重设文件光标,但是在大多数情况下,您应该只对文件进行一次迭代.

It is not only an iterable, it is an iterator, which is why it can only traverse the file once. You may reset the file cursor with .seek(0) as many have suggested but you should, in most cases, only iterate a file once.

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

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