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
以上就是Python流式读取大文件的两种方法,更多Python学习教程请关注IT培训机构:千锋教育。

猜你喜欢LIKE
相关推荐HOT
更多>>
python里glob模块怎么用?
python里glob模块怎么用?本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。简单介绍:匹配一定的格式文件和文件夹。包含函数:1、glo...详情>>
2023-11-14 23:59:20
python中time.gmtime是什么
python中time.gmtime是什么下面我们就time.gmtime函数的概念、语法、参数、返回值、实例分别进行讲解。1.概念gmtime是把日期和时间转换为格林威...详情>>
2023-11-14 21:58:02
python使用OpenCV画图
python中使用OpenCV画图OpenCV的强大之处的一个体现就是其可以对图片进行任意编辑,处理。下面的这个函数最后一个参数指定的就是画笔的大小1、...详情>>
2023-11-14 19:49:08
python流式读取大文件的两种方法
python流式读取大文件的两种方法1、使用read方法分块读取使用更底层的file.read()方法,与直接循环迭代文件对象不同,每次调用file.read(chunk_...详情>>
2023-11-14 16:48:08热门推荐
python里glob模块怎么用?
沸python中series转dataframe的两种方法
热python实现矩阵乘法运算的几种方法
热pandas遍历dataframe的方法有哪些
新python中time.gmtime是什么
python中RNN和LSTM的基本介绍
Python中for循环进行字典迭代
Python中哈希结构有哪几种?
python使用OpenCV画图
python绝对和相对导入的介绍
python标识符是什么意思?
python中如何查看stdin编码?
python如何访问列表元素?
python如何提取文本信息?
技术干货






