[英]What's the difference between “for x in file/file.readlines()”
According to the type, file is a function and file.readlines() is a list of lines. 根据类型,文件是一个函数,而file.readlines()是一个行列表。 But why do these two generate the same results in the following code:
但是,为什么这两个在以下代码中产生相同的结果:
file = open("test.txt")
for x in file:
print x
and 和
file = open("test.txt")
for x in file.readlines():
print x
readlines()
reads the entire file into a list()
, over which you then iterate using for
. readlines()
将整个文件读入list()
,然后使用for
进行迭代。 But, you can also just iterate over the file
object itself, which will cause it to read one line at a time with each iteration of the loop. 但是,您也可以仅遍历
file
对象本身,这会使它在循环的每次迭代中一次读取一行。 That's much more efficient, since it won't store the entire file's contents in memory at once. 这样效率更高,因为它不会立即将整个文件的内容存储在内存中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.