python读取大文件处理方式
2016-10-11 16:07
495 查看
一.前言
我们在处理小的文本文件时一般使用
二.解决办法
1.看到文件这么大,我们的第一反应都是把文件分割成小块的读取不就好了吗
2.使用
3.fileinput处理
参考:http://chenqx.github.io/2014/10/29/Python-fastest-way-to-read-a-large-file/
http://www.zhidaow.com/post/python-read-big-file
我们在处理小的文本文件时一般使用
.read()、
.readline()和
.readlines(),当我们的文件有10个G甚至更大时,用上面的方法内存就直接爆掉了。
二.解决办法
1.看到文件这么大,我们的第一反应都是把文件分割成小块的读取不就好了吗
def read_in_chunks(filePath, chunk_size=1024*1024): """ Lazy function (generator) to read a file piece by piece. Default chunk size: 1M You can set your own chunk size """ file_object = open(filePath) while True: chunk_data = file_object.read(chunk_size) if not chunk_data: break yield chunk_data if __name__ == "__main__": filePath = './path/filename' for chunk in read_in_chunks(filePath): process(chunk) # <do something with chunk>
2.使用
with open()
#If the file is line based with open(...) as f: for line in f: process(line) # <do something with line>
3.fileinput处理
import fileinput for line in fileinput.input(['sum.log']): print line
参考:http://chenqx.github.io/2014/10/29/Python-fastest-way-to-read-a-large-file/
http://www.zhidaow.com/post/python-read-big-file
相关文章推荐
- Python文件处理之文件读取方式(二)
- C# Python 读取txt中的文件,将16进制的数据按照小端方式排列,处理为有符号的数字,并写入text文件;控制台和界面两种方式
- python读取文件时遇到非法字符的处理 UnicodeDecodeError: 'gbk' codec can't decode bytes in position
- python 大文件以行为单位读取方式比对
- python文件操作之文件读取方式
- [转]python 大文件以行为单位读取方式比对
- python文件处理方式
- [libexpat]_[XML处理]_[C/C++使用libexpat库以数据流(SAX模型)的方式读取(解析)大XML文件]
- python 大文件以行为单位读取方式比对
- python实现带错误处理功能的远程文件读取方法
- Python文件处理之文件打开方式(一)
- python中三种处理文件输出的方式
- C# 读取压缩文件方式及乱码处理
- 一种处理从文件读取整数的方式
- python文件处理:读取文件
- matlab处理txt文本文件---数据格式要有规律性,否则要用编写特定方式进行读取
- MATLAB处理txt文本文件---数据格式要有规律性,否则要用编写特定方式进行读取
- IDEA读取本地文件进行处理的方式
- Python 读取键盘输入字符,多线程操作,文件操作随机处理 开发范例
- python对文件的读取操作方式比较