强悍的Python读取大文件的解决方案
作者:Inside_Zhang 时间:2021-12-26 19:25:28
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
来源:https://blog.csdn.net/lanchunhui/article/details/51581540
标签:python,读取大文件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
关于Pytorch中模型的保存与迁移问题
2023-08-11 04:05:25
OpenCV计算平均值cv::mean实例代码
2023-06-19 10:26:02
![](https://img.aspxhome.com/file/2023/3/59833_0s.png)
python接口调用已训练好的caffe模型测试分类方法
2021-08-11 18:31:04
![](https://img.aspxhome.com/file/2023/7/70107_0s.jpg)
潜谈产品设计中的可用性和可访问性
2009-01-18 12:47:00
![](https://img.aspxhome.com/file/UploadPic/20091/18/prdocut_reg-60s.jpg)
Oracle 中文字段进行排序的sql语句
2009-09-26 18:58:00
三谈Iframe自适应高度
2010-08-03 13:04:00
Python依赖包整体迁移方法详解
2022-11-03 05:32:55
![](https://img.aspxhome.com/file/2023/8/68998_0s.jpg)
Django模板获取field的verbose_name实例
2023-07-30 06:53:55
Python字符串中如何去除数字之间的逗号
2023-12-01 22:09:48
Python通过DOM和SAX方式解析XML的应用实例分享
2023-10-15 10:46:32
多个域名后缀同时查询的域名查询系统代码
2008-05-20 11:53:00
一个不错的网页拾色器
2007-09-30 19:45:00
![](https://img.aspxhome.com/file/UploadPic/20079/30/2007930201019921s.jpg)
简单的PHP缓存设计实现代码
2023-10-25 19:58:08
asp如何读取Access数据库的表名?
2009-11-18 20:48:00
Python数据清洗工具之Numpy的基本操作
2023-08-31 02:39:10
![](https://img.aspxhome.com/file/2023/0/66300_0s.png)
从网页设计开始
2008-06-30 12:17:00
Python在线和离线安装第三方库的方法
2023-08-24 19:37:11
![](https://img.aspxhome.com/file/2023/8/62868_0s.png)
深入讲解Go语言中函数new与make的使用和区别
2023-06-16 17:52:29
番茄的js表单验证类
2008-01-07 13:53:00
Python爬虫制作翻译程序的示例代码
2023-08-13 06:38:35
![](https://img.aspxhome.com/file/2023/5/78725_0s.jpg)