
python 一个文件太大+内存装不下+怎么读取 mongo
Python 环境下文件的读取问题,请参见拙文 Python 基础 —— 文件
这是一道著名的 Python 面试题,考察的问题是,Python 读取大文件和一般规模的文件时的区别,也即哪些接口不适合读取大文件。
1. read() 接口的问题
f = open(filename, 'rb')
f.read()12
我们来读取 1 个 nginx 的日至文件,规模为 3Gb 大小。read() 方法执行的操作,是一次性全部读入内存,显然会造成:
MemoryError...12
也即会发生内存溢出。
2. 解决方案:转换接口
(1)readlines() :读取全部的行,构成一个 list,实践表明还是会造成内存的问题;
for line in f.reanlines(): ...1
2
(2)readline():每次读取一行,
while True:
line = f.readline() if not line: break1
2
3
4
(3)read(1024):重载,指定每次读取的长度
while True: block = f.read(1024) if not block: break1
2
3
4
- with open(filename, 'rb') as f: for line in f:
- <do something with the line>123
3. 真正 Pythonic 的方法
真正 Pythonci 的方法,使用 with 结构:
对可迭代对象 f,进行迭代遍历:for line in f,会自动地使用缓冲IO(buffered IO)以及内存管理,而不必担心任何大文件的问题。
There should be one – and preferably only one – obvious way to do it.