python 读取大文件_Python读取大文件
1. 前言
前幾天在做日志分析系統,需要處理幾十G的文件,我嘗試用原來的for line in open(filepath).readlines()處理,但停頓好久也沒變化,可見占用不小的內存。在網上搜索了下,找到了兩種方法來讀取大文件。
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,更推薦使用。
總結
以上是生活随笔為你收集整理的python 读取大文件_Python读取大文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: asp从后台调出的公式怎么参与运算_吴望
- 下一篇: html li标签横向排列_HTML简易