python 读取大文件_Python读取大文件

1. 前言

前几天在做日志分析系统,需要处理几十G的文件,我尝试用原来的for line in open(filepath).readlines()处理,但停顿好久也没变化,可见占用不小的内存。在网上搜索了下,找到了两种方法来读取大文件。

python-icon.png

2. with读取大文件

with读取是非常Pythonic的方法,示例如下:

with open(filepath) as f:

for line in f:

这个方法是在Stackoverflow上找到,这位高手对with读取的解释是这样的:

The with statement handles opening and closing the file, including if an exception is raised in the inner block. The for line in f treats the file object f as an iterable, which automatically uses buffered IO and memory management so you don't have to worry about large files.

大意就是with负责处理open和close文件,包括抛出内部异常。而for line in f将文件对象f当做迭代对象,将自动处理IO缓冲和内存管理,这样你无需担心大文件的处理了。

3. fileinput处理

用到了Python的fileinput模块,亲测也毫无卡顿,示例代码如下:

import fileinput

for line in fileinput.input(['sum.log']):

print line

4. 总结

以上两种方法都亲测可用,明显第一种更Pythonic,无需import,而且还能处理close和Exception,更推荐使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值