强悍的 Python —— 读取大文件

                       

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

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

1. read() 接口的问题

f = open(filename, 'rb')f.read()
   
   
  • 1
  • 2

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

MemoryError...
   
   
  • 1
  • 2

也即会发生内存溢出。

2. 解决方案:转换接口

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

    for line in f.reanlines():    ...
         
         
    • 1
    • 2
  • (2)readline():每次读取一行,

    while True:    line = f.readline()    if not line:        break
         
         
    • 1
    • 2
    • 3
    • 4
  • (3)read(1024):重载,指定每次读取的长度

    while True:    block = f.read(1024)    if not block:        break
         
         
    • 1
    • 2
    • 3
    • 4

3. 真正 Pythonic 的方法

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

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

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

 

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

Reference

  1. How to read large file, line by line in python
           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自blog.csdn.net/qq_43679627/article/details/87637958