python读取大文件

  1. 较pythonic的方法,使用with结构

    • 文件可以自动关闭
    • 异常可以在with块内处理
        with open(filename, 'rb') as f:
    for line in f:
    <do someting with the line>

最大的优点:对可迭代对象 f,进行迭代遍历:for line in f,会自动地使用缓冲IO(buffered IO)以及内存管理,而不必担心任何大文件的问题。

There should be one – and preferably only one – obvious way to do it.

  1. 使用生成器generator

如果想对每次迭代读取的内容进行更细粒度的处理,可以使用yield生成器来读取大文件

    def readInChunks(file_obj, chunkSize=2048):
"""
Lazy function to read a file piece by piece.
Default chunk size: 2kB.
"""
while True:
data = file_obj.read(chunkSize)
if not data:
break
yield data
f = open('bigFile')
for chunk in readInChunks(f):
do_something(chunk)
f.close()
  1. linux下使用split命令(将一个文件根据大小或行数平均分成若干个小文件)
    wc -l BLM.txt  # 读出BLM.txt文件一共有多少行
# 利用split进行分割
split -l 2482 ../BLM/BLM.txt -d -a 4 BLM_
# 将 文件 BLM.txt 分成若干个小文件,每个文件2482行(-l 2482),文件前缀为BLM_ ,系数不是字母而是数字(-d),后缀系数为四位数(-a 4) # 按行数分割
split -l 300 large_file.txt new_file_prefix
# 文件大小分割
split -b 10m server.log waynelog # 对文件进行合并:使用重定向,'>' 写入文件 , '>>' 追加到文件中
cat file_prefix* > large_file

在工作中的日常: 用户信息,log日志缓存,等都是大文件

补充:linecache模块

当读取一个文件的时候,python会尝试从缓存中读取文件内容,优化读取速度,提高效率,减少了I/O操作

linecache.getline(filename, lineno) 从文件中读取第几行,注意:包含换行符

linecache.clearcache() 清除现有的文件缓存

linecache.checkcache(filename=None) 检查缓存内容的有效性,可能硬盘内容发生改变,更新了,如果没有参数,将检查缓存中的所有记录(entries)

    import linecache
linecache.getline(linecache.__file__, 8)

题目:

现给一个文件400M(该文件是由/etc/passwd生成的),统计其中root字符串出现的次数

    import time
sum = 0
start = time.time()
with open('file', 'r') as f:
for i in f:
new = i.count('root')
sum+=new
end = time.time()
print(sum, end-start)

:有时候这个程序比c,shell快10倍,原因就是,python会读取cache中的数据,使用缓存在内部进行优化,减少i/o,提高效率

References : How to read a large file

Read a large file with python的更多相关文章

  1. Read Large Files in Python

    I have a large file ( ~4G) to process in Python. I wonder whether it is OK to "read" such ...

  2. Github Upload Large File 上传超大文件

    Github中单个文件的大小限制是100MB,为了能突破这个限制,我们需要使用Git Large File Storage这个工具,参见这个官方帖子,但是按照其给的步骤,博主未能成功上传超大文件,那么 ...

  3. read content in a text file in python

    ** read text file in pythoncapability: reading =text= from a text file 1. open the IDLE text editor  ...

  4. Combining an audio file with video file in python

    Combining an audio file with video file in python - Stack Overflow https://stackoverflow.com/questio ...

  5. Java – Reading a Large File Efficiently--转

    原文地址:http://www.baeldung.com/java-read-lines-large-file 1. Overview This tutorial will show how to r ...

  6. [PySpark] RDD programming on a large file

    重难点 一.parallelize 方法 一般来说,Spark会尝试根据集群的状况,来自动设定slices的数目.然而,你也可以通过传递给parallelize的第二个参数来进行手动设置. data_ ...

  7. download file by python in google colab

    https://stackoverflow.com/questions/15352668/download-and-decompress-gzipped-file-in-memory You need ...

  8. How do I get the path of the current executed file in Python?

    First, you need to import from inspect and os from inspect import getsourcefile from os.path import ...

  9. Base64 encode/decode large file

    转载:http://www.cnblogs.com/jzywh/archive/2008/04/20/base64_encode_large_file.html The class System.Co ...

随机推荐

  1. xfs参数简介

    age_buffer_centisecs age_buffer_centisecs:(Min: 100  Default: 1500  Max: 720000) 多长时间设置为脏数据 xfsbufd_ ...

  2. Android解析WindowManagerService(二)WMS的重要成员和Window的添加过程

    前言 在本系列的上一篇文章中,我们学习了WMS的诞生,WMS被创建后,它的重要的成员有哪些?Window添加过程的WMS部分做了什么呢?这篇文章会给你解答. 1.WMS的重要成员 所谓WMS的重要成员 ...

  3. CoolViewPager:即刻刷新,自定义边缘效果颜色,双向自动循环,内置垂直切换效果,想要的都在这里

    这两天在GitHub上传了一个自定义ViewPager:CoolViewPager,具有以下功能特征: 支持水平及垂直方向循环滚动 支持自动滚动 支持自动滚动方向.滚动时间.间隔时间的设置 支持调用n ...

  4. PG数据库空间大小及数据库对象占用空间大小

    select pg_size_pretty(pg_database_size('lrisk')); --查询数据库剩余空间 select pg_database.datname,pg_size_pre ...

  5. Castle.Windsor IOC/AOP的使用

    Castle最早在2003年诞生于Apache Avalon项目,目的是为了创建一个IOC(控制反转)框架.发展到现在已经有4个组件了,分别是ActiveRecord(ORM组件).Windsor(I ...

  6. 用POP动画模拟真实秒钟摆动效果

    用POP动画模拟真实秒钟摆动效果 静态图: 动画图: 此处用到了POP中的Spring系列动画,现提供源码如下: SecondClockView.h 与 SecondClockView.m // // ...

  7. 3D旋转相册的实现

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  8. 安装office2016和激活。

    严重声明:条件宽裕的同学可以购买正版.请大家多多支持正版. 自己手贱,原本在电脑win10系统上安装的正版office被误删了,联系了客服人员,但是自己的微软账号也忘记了.好想下载个正版的.自己在网上 ...

  9. 10个值得深思的PHP面试题

    第一个问题关于弱类型 $str1 = 'yabadabadoo'; $str2 = 'yaba'; if (strpos($str1,$str2)) { echo "/"" ...

  10. July 28th 2017 Week 30th Friday

    If equal affection cannot be, let the more loving be me. 如果没有相等的爱,那就让我爱多一点吧. There is seldom equal a ...