Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python for循环在文件对象上做什么?_Python_Python 2.7 - Fatal编程技术网

Python for循环在文件对象上做什么?

Python for循环在文件对象上做什么?,python,python-2.7,Python,Python 2.7,对于循环和文件,我有一个与Python相关的问题 在此代码中: file = raw_input("input a text file ") f = open(file) # creates a file object of file for line in f: # prints each line in the file print line print f # prints <open file 'MVL_ref.txt', mode 'r' at 0

对于循环和文件,我有一个与Python相关的问题

在此代码中:

file = raw_input("input a text file ")

f = open(file) #  creates a file object of file

for line in f:
    # prints each line in the file
    print line 



print f

# prints <open file 'MVL_ref.txt', mode 'r' at 0x0267D230>

print f.read() # same output of the for-cycle
print f.readline() # same output of the for-cycle
当然,情况并非如此。 如果在没有for循环的情况下使用read或readline方法,则会得到与for循环相同的输出

for循环是否有一些神奇的功能,比如在文件对象上默认调用read()或readline()?我正在学习如何使用python编写代码,但我觉得我并不真正理解“在我背后”代码在做什么


感谢您将要提供的所有解释。

因为Python中的文件对象是一个对象,所以您可以对它进行迭代以逐个获得文件行

然而,文件不是一个集合,而是一个对象——当输出集合时,通过像这样打印,您不会看到所有的行

l = ["line1", "line2"]
print l 
但您将看到实体描述

<open file 'path_to_the_file', mode 'r' at 0x0245D020>


注释准确地说明了它在做什么,不是吗?
对于f.read()中的行:
。。。不要混淆变量名。这些不是行,这些是单个字符。这实际上取决于txt文件中的内容,如果行已使用换行符“\n”分隔,则无需使用.read()方法。具体到这一部分,在处理文件对象时使用
with
关键字是一种很好的做法。感谢您的解释。换句话说,在for循环中,file对象的行为类似于collectionYes,因为它可以返回迭代器,让你一行一行地获取你的最后一个答案让我寻找迭代器、iterable、iter、next和其他东西。在循环的背后确实发生了很多我完全忽略的事情。谢谢你,伙计!很高兴帮助您:)
<open file 'path_to_the_file', mode 'r' at 0x0245D020>