首页IT科技python读取文件流(Python流式读取大文件的两种方法)

python读取文件流(Python流式读取大文件的两种方法)

时间2025-08-04 22:02:03分类IT科技浏览3727
导读:Python流式读取大文件的两种方法...

Python流式读取大文件的两种方法

1            、使用 read 方法分块读取

使用更底层的file.read()方法            ,与直接循环迭代文件对象不同                   ,每次调用file.read(chunk_size)会直接返回从当前位置往后读取 chunk_size 大小的文件内容       ,不必等待任何换行符出现            。

defcount_nine_v2(fname): """计算文件里包含多少个数字9      ,每次读取8kb """ count=0 block_size=1024*8 withopen(fname)asfp: whileTrue: chunk=fp.read(block_size) #当文件没有更多内容时                   ,read调用将会返回空字符串 ifnotchunk: break count+=chunk.count(9) returncount

2                   、利用生成器解耦代码

可以定义一个新的chunked_file_reader生成器函数             ,由它来负责所有与“数据生成             ”相关的逻辑                   。

count_nine_v3里面的主循环就只需要负责计数即可       。

defchunked_file_reader(fp,block_size=1024*8): """生成器函数:分块读取文件内容 """ whileTrue: chunk=fp.read(block_size) #当文件没有更多内容时      ,read调用将会返回空字符串 ifnotchunk: break yieldchunk defcount_nine_v3(fname): count=0 withopen(fname)asfp: forchunkinchunked_file_reader(fp): count+=chunk.count(9) returncount

使用 iter(callable,sentinel) 的方式调用它时                   ,会返回一个特殊的对象             ,迭代它将不断产生可调用对象 callable 的调用结果,直到结果为 setinel 时                   ,迭代终止      。

defchunked_file_reader(file,block_size=1024*8): """生成器函数:分块读取文件内容                    ,使用iter函数 """ #首先使用partial(fp.read,block_size)构造一个新的无需参数的函数 #循环将不断返回fp.read(block_size)调用结果,直到其为时终止 forchunkiniter(partial(file.read,block_size),): yieldchunk

创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

展开全文READ MORE
Django框架MVT开发模型的认识(django框架(部分讲解))