python - 迭代二进制文件的惯用方法是什么?

标签 python file iterator

使用文本文件,我可以这样写:

with open(path, 'r') as file:
    for line in file:
        # handle the line

这等价于:

with open(path, 'r') as file:
    for line in iter(file.readline, ''):
        # handle the line

这个成语记录在 PEP 234但我没有找到类似的二进制文件习语。

使用二进制文件,我可以这样写:

with open(path, 'rb') as file:
    while True:
        chunk = file.read(1024 * 64)
        if not chunk:
            break
        # handle the chunk

我尝试过与文本文件相同的习语:

def make_read(file, size):
    def read():
        return file.read(size)
    return read

with open(path, 'rb') as file:
    for chunk in iter(make_read(file, 1024 * 64), b''):
        # handle the chunk

这是在 Python 中迭代二进制文件的惯用方式吗?

最佳答案

试试:

chunk_size = 4 * 1024 * 1024  # MB

with open('large_file.dat','rb') as f:
    for chunk in iter(lambda: f.read(chunk_size), b''):
        handle(chunk)

iter需要一个零参数的函数。

  • 一个普通的 f.read将读取整个文件,因为缺少 size 参数;
  • f.read(1024) 表示调用函数并将其返回值(从文件加载的数据)传递给iter,所以iter根本没有功能;
  • (lambda:f.read(1234)) 是一个接受零参数的函数(lambda: 之间没有任何参数)并调用f.read(1234).

关于python - 迭代二进制文件的惯用方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4566498/

相关文章:

python - 线性回归预测预测输入数据(测试数据),而不是测试结果

java - 将字节数组作为图像或文件从 Java 写入 MySQL 数据库

python - 用于文件操作的 R 或 Python

collections - 为什么不能收集一系列字符?

python - 使用 reportlab 将图像放入 pdf 时提高图像质量

python - 是否可以在 headless 模式下使用 CEF python 进行屏幕截图?

python - Django 教程,获取 : TypeError at/admin/argument to reversed() must be a sequence

javascript - 如何使用未知编码jquery编码为utf文本文件

python - 内置函数 iter() 如何将 Python 列表转换为迭代器?

Android Realm 迭代器异常