
Python流式读取大文件的两种方法
1、使用 read 方法分块读取
使用更底层的file.read()方法,与直接循环迭代文件对象不同,每次调用file.read(chunk_size)会直接返回从当前位置往后读取 chunk_size 大小的文件内容,不必等待任何换行符出现。
1 2 3 4 5 6 7 8 9 10 11 12 13 | def count_nine_v2(fname):
"" "计算文件里包含多少个数字 '9' ,每次读取 8kb
"" "
count = 0
block_size = 1024 * 8
with open(fname) as fp:
while True:
chunk = fp.read(block_size)
# 当文件没有更多内容时,read 调用将会返回空字符串 ''
if not chunk:
break
count += chunk. count ( '9' )
return count
|
2、利用生成器解耦代码
可以定义一个新的chunked_file_reader生成器函数,由它来负责所有与“数据生成”相关的逻辑。
count_nine_v3里面的主循环就只需要负责计数即可。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | def chunked_file_reader(fp, block_size=1024 * 8):
"" "生成器函数:分块读取文件内容
"" "
while True:
chunk = fp.read(block_size)
# 当文件没有更多内容时,read 调用将会返回空字符串 ''
if not chunk:
break
yield chunk
def count_nine_v3(fname):
count = 0
with open(fname) as fp:
for chunk in chunked_file_reader(fp):
count += chunk. count ( '9' )
return count
|
使用 iter(callable,sentinel) 的方式调用它时,会返回一个特殊的对象,迭代它将不断产生可调用对象 callable 的调用结果,直到结果为 setinel 时,迭代终止。
1 2 3 4 5 6 7 | def chunked_file_reader(file, block_size=1024 * 8):
"" "生成器函数:分块读取文件内容,使用 iter 函数
"" "
# 首先使用 partial(fp.read, block_size) 构造一个新的无需参数的函数
# 循环将不断返回 fp.read(block_size) 调用结果,直到其为 '' 时终止
for chunk in iter(partial(file.read, block_size), '' ):
yield chunk
|
以上就是Python流式读取大文件的两种方法,希望能对你有所帮助哟~