当前位置:主页 > 软件编程 > Python代码 >

强悍的Python读取大文件的解决方案

时间:2021-05-02 08:20:43 | 栏目:Python代码 | 点击:

Python 环境下文件的读取问题,请参见拙文 Python基础之文件读取的讲解

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

1. read() 接口的问题

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

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

MemoryError
...

也即会发生内存溢出。

2. 解决方案:转换接口

for line in f.reanlines():
  ...
while True:
  line = f.readline()
  if not line:
    break
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 ?C and preferably only one ?C obvious way to do it.

Reference

How to read large file, line by line in python

总结

您可能感兴趣的文章:

相关文章