您的位置:首页 > 编程语言 > Python开发

强悍的 Python —— 读取大文件

2016-06-03 20:31 766 查看
Python 环境下文件的读取问题,请参见拙文 Python 基础 —— 文件

这是一道著名的 Python 面试题,考察的问题是,Python 读取大文件和一般规模的文件时的区别,也即哪些接口不适合读取大文件。

1. read() 接口的问题

f = open(filename, 'rb')
f.read()


我们来读取 1 个 nginx 的日至文件,规模为 3Gb 大小。read() 方法执行的操作,是一次性全部读入内存,显然会造成:

MemoryError
...


也即会发生内存溢出。

2. 解决方案:转换接口

(1)readlines() :读取全部的行,构成一个 list,实践表明还是会造成内存的问题;

for line in f.reanlines():
...


(2)readline():每次读取一行,

while True:
line = f.readline()
if not line:
break


(3)read(1024):重载,指定每次读取的长度

while True:
block = f.read(1024)
if not block:
break


3. 真正 Pythonic 的方法

真正 Pythonci 的方法,使用 with 结构:

with open(filename, 'rb') as f:
for line in f:
<do something with the line>


对可迭代对象 f,进行迭代遍历:
for line in f
,会自动地使用缓冲IO(buffered IO)以及内存管理,而不必担心任何大文件的问题。

There should be one – and preferably only one – obvious way to do it.

Reference

How to read large file, line by line in python
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: