之间的区别:"file.readlines()","list(file)"和"file.read().splitlines(True)"? [英] Is there a difference between : "file.readlines()", "list(file)" and "file.read().splitlines(True)"?
本文介绍了之间的区别:"file.readlines()","list(file)"和"file.read().splitlines(True)"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
之间的区别是什么:
with open("file.txt", "r") as f:
data = list(f)
或:
with open("file.txt", "r") as f:
data = f.read().splitlines(True)
或:
with open("file.txt", "r") as f:
data = f.readlines()
它们似乎产生完全相同的输出. 一个比另一个更好(或更pythonic)吗?
They seem to produce the exact same output. Is one better (or more pythonic) than the other ?
推荐答案
显式比隐式好,所以我更喜欢:
Explicit is better than implicit, so I prefer:
with open("file.txt", "r") as f:
data = f.readlines()
但是,在可能的情况下,最Python化的是直接使用文件迭代器,而无需将所有内容加载到内存中,例如:
But, when it is possible, the most pythonic is to use the file iterator directly, without loading all the content to memory, e.g.:
with open("file.txt", "r") as f:
for line in f:
my_function(line)
这篇关于之间的区别:"file.readlines()","list(file)"和"file.read().splitlines(True)"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文