我有一个大文件要阅读和处理。
这是读取和处理文件的更快方法。
with open('file') as file:
for line in file:
print line
或者
file = open('file')
lines = f.readlines()
file.close()
for line in lines:
print line
我有一个大文件要阅读和处理。
这是读取和处理文件的更快方法。
with open('file') as file:
for line in file:
print line
或者
file = open('file')
lines = f.readlines()
file.close()
for line in lines:
print line
前者可以使用缓冲读取;后者需要先将整个文件读入内存,然后才能开始循环。
一般来说,使用前者会更好。它不会比后者慢,并且在内存使用方面更好。
如果您有一些基于行的大文件,我强烈建议使用以下行来实现您的目标:
file = open('file')
for line in f.readlines():
print line
file.close()
有2点,
PS: The former "with" statement only is short for try:open();execept:pass
; readlines is implemented using iterator, so it won't eat all your memory.