流式读取数G超大文件
流式读取数G超大文件
使用 with…open… 可以从一个文件中读取数据,这是所有 Python 开发者都非常熟悉的操作。
但是如果你使用不当,也会带来很大的麻烦。
比如当你使用了 read 函数,其实 Python 会将文件的内容一次性的全部载入内存中,如果文件有 10 个G甚至更多,那么你的电脑就要消耗的内存非常巨大。
- 一次性读取
with open("big_file.txt", "r") as fp:
content = fp.read()
- 逐行读取
def read_from_file(filename):
with open(filename, "r") as fp:
yield fp.readline()
- 指定每次读取的大小
def read_from_file(filename, block_size = 1024 * 8):
with open(filename, "r") as fp:
while True:
chunk = fp.read(block_size)
if not chunk:
break
yield chunk
# or
from functools import partial
def read_from_file(filename, block_size = 1024 * 8):
with open(filename, "r") as fp:
for chunk in iter(partial(fp.read, block_size), ""):
yield chunk