Python读大数据txt
作者:hebedich 时间:2021-12-29 20:34:12
如果直接对大文件对象调用 read() 方法,会导致不可预测的内存占用。好的方法是利用固定长度的缓冲区来不断读取文件内容。即通过yield。
在用Python读一个两个多G的txt文本时,天真的直接用readlines方法,结果一运行内存就崩了。
还好同事点拨了下,用yield方法,测试了下果然毫无压力。咎其原因,原来是readlines是把文本内容全部放于内存中,而yield则是类似于生成器。
代码如下:
def open_txt(file_name):
with open(file_name,'r+') as f:
while True:
line = f.readline()
if not line:
return
yield line.strip()
调用实例:
for text in open_txt('aa.txt'):
print text
例二:
目标 txt 文件大概有6G,想取出前面1000条数据保存于一个新的 txt 文件中做余下的操作,虽然不知道这样做有没有必要但还是先小数据量测试一下吧。参考这个帖子:我想把一个list列表保存到一个Txt文档,该怎么保存 ,自己写了一个简单的小程序。
====================================================
import datetime
import pickle
start = datetime.datetime.now()
print "start--%s" % (start)
fileHandle = open ( 'train.txt' )
file2 = open('s_train.txt','w')
i = 1
while ( i < 10000 ):
a = fileHandle.readline()
file2.write(''.join(a))
i = i + 1
fileHandle.close()
file2.close()
print "done--%s" % ( datetime.datetime.now() - start)
if __name__ == '__main__':
pass
====================================================
pickle 这个库大家说的很多,官网看看,后面可以好好学习一下。
标签:Python,txt
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python使用conda如何安装requirement.txt的扩展包
2022-03-13 23:01:18
一篇文章彻底搞懂Python中可迭代(Iterable)、迭代器(Iterator)与生成器(Generator)的概念
2023-11-03 23:52:38
javascript的正则表达式
2010-07-27 12:29:00
中英文双语导航菜单
2007-05-11 17:04:00
![](https://img.aspxhome.com/file/UploadPic/20075/20075111747385s.gif)
opencv python截取圆形区域的实现
2022-11-27 06:58:50
![](https://img.aspxhome.com/file/2023/7/87997_0s.jpg)
CSS代码实现下划线样式的输入框效果
2010-03-16 12:42:00
![](https://img.aspxhome.com/file/UploadPic/20103/16/201031613047449s.jpg)
python中itertools模块zip_longest函数详解
2023-01-02 09:09:35
Python对多个sheet表进行整合实例讲解
2021-01-15 06:18:24
Python简单计算文件MD5值的方法示例
2023-06-07 06:06:42
一篇文章搞懂python混乱的切换操作与优雅的推导式
2023-09-15 00:25:10
![](https://img.aspxhome.com/file/2023/9/99549_0s.png)
解决python对齐错误的方法
2023-08-11 05:40:07
![](https://img.aspxhome.com/file/2023/8/98928_0s.jpg)
在Python的Bottle框架中使用微信API的示例
2022-06-02 00:12:47
![](https://img.aspxhome.com/file/2023/8/105808_0s.jpg)
Python可视化神器pyecharts绘制饼状图
2023-11-27 17:06:18
![](https://img.aspxhome.com/file/2023/1/63551_0s.png)
在Python中使用lambda高效操作列表的教程
2023-08-02 04:42:53
关于淘宝商城新版的一点看法
2009-06-28 16:00:00
![](https://img.aspxhome.com/file/UploadPic/20096/28/taobao_mall_2-49s.png)
php 无法载入mysql扩展
2023-09-07 13:07:40
python获取酷狗音乐top500的下载地址 MP3格式
2021-05-06 04:38:05
![](https://img.aspxhome.com/file/2023/9/78819_0s.jpg)
用 iframe 解决下拉框与层之冲突
2008-04-28 12:24:00
![](https://img.aspxhome.com/file/UploadPic/20071/2007131102430882s.gif)
Python函数参数定义及传递方式解析
2021-10-19 21:28:25
利用后缀表达式(逆波兰式)算24点的JavaScript版算法
2010-01-23 10:57:00