简体   繁体   English

“ for file / file.readlines()中的x”有什么区别?

[英]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.

相关问题 “file.readlines()”、“list(file)”和“file.read().splitlines(True)”之间有区别吗? - Is there a difference between : “file.readlines()”, “list(file)” and “file.read().splitlines(True)”? 在python中的file.readlines()中搜索子字符串 - Searching for substrings in file.readlines() in python 使用 file.readlines() 后删除不需要的字符 - Remove unwanted characters after using file.readlines() 无法使用 file.readlines() 读取原始电子邮件数据 - Unable to read raw email data using file.readlines() 尽管seek(0),file.readlines()返回一个空列表 - file.readlines() returns an empty list despite seek(0) 我什么时候应该使用 file.read() 或 file.readlines()? - When should I ever use file.read() or file.readlines()? os.system的行为与raw_input()和file.readlines()的输入不同 - os.system behaves differently w/ input from raw_input() vs file.readlines() 'in fp'和'in fp.readlines()'之间有什么区别? - What is the difference between 'in fp' and 'in fp.readlines()'? Python - “in”和“in x for x in”之间的区别是什么 - Python - What's the difference between “in” and “in x for x in” 什么是从Python文件中读取内容的更好方法? - What is a better way to readlines from Python file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM