def read_in_chunks(file_object, chunk_size=1024):
"""Lazy function (generator) to read a file piece by piece.
Default chunk size: 1k."""
while True:
data = file_object.read(chunk_size)
if not data:
break
yield data
with open('path/to/file', 'r') as f:
for piece in read_in_chunks(f):
print piece
逐行读取
在某些情况下,我们希望逐行读取文件,这时可以使用 readline() 方法。
看看例子:
with open('data.txt', 'r') as f:
while True:
line = f.readline() # 逐行读取
if not line:
break
print line, # 这里加了 ',' 是为了避免 print 自动换行