强悍的 Python —— 读取大文件
2016-06-03 20:31
766 查看
Python 环境下文件的读取问题,请参见拙文 Python 基础 —— 文件
这是一道著名的 Python 面试题,考察的问题是,Python 读取大文件和一般规模的文件时的区别,也即哪些接口不适合读取大文件。
我们来读取 1 个 nginx 的日至文件,规模为 3Gb 大小。read() 方法执行的操作,是一次性全部读入内存,显然会造成:
也即会发生内存溢出。
(2)readline():每次读取一行,
(3)read(1024):重载,指定每次读取的长度
对可迭代对象 f,进行迭代遍历:
There should be one – and preferably only one – obvious way to do it.
这是一道著名的 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相关文章推荐
- Ubuntu部署python3.5的开发和运行环境
- Python 读取文件夹下文件列表 自然排序
- Win10安装Python出错: there is a problem with widows installer package,a program run as part of setup di
- python中的除法,取整和求模
- python 学习day4
- Python循环语句for和while
- python data analysis | python数据预处理(基于scikit-learn模块)
- Python中遇到"UnicodeDecodeError: ‘gbk’ codec can’t decode bytes in position 2-3: illegal multibyte sequ
- python——赋值与深浅拷贝
- vim 配置 python IDE 开发环境
- Python爬虫下载网站上的图片到本地
- Python的Django中将文件上传至七牛云存储的代码分享
- python开源机器学习工具scikit中文教程
- Python学习笔记 —— 运算符
- Python
- 基于 Python 和 Scikit-Learn 的机器学习介绍
- python中decorator
- My Library
- Python - 练习 判断输入是奇数,偶数,小数,还是字符
- Python实现遍历url