【问题标题】:Fastest way to read a large binary file with Python使用 Python 读取大型二进制文件的最快方法
【发布时间】:2020-02-01 04:51:40
【问题描述】:

我需要在 Python 3.6 中读取一个简单但很大 (500MB) 的二进制文件。该文件由 C 程序创建,包含 64 位双精度数据。我尝试使用 struct.unpack ,但对于大文件来说这非常慢。

这是我读取的简单文件:

def ReadBinary():

    fileName = 'C:\\File_Data\\LargeDataFile.bin'

    with open(fileName, mode='rb') as file:
        fileContent = file.read()

现在我有了文件内容。将其解码为 64 位双精度浮点或无需进行格式转换即可读取的最快方法是什么?

如果可能,我想避免分块读取文件。我想像 C 一样一次读取它解码的内容。

【问题讨论】:

标签: python python-3.x


【解决方案1】:

你可以使用array.array('d')'sfromfile方法:

def ReadBinary():
    fileName = r'C:\File_Data\LargeDataFile.bin'

    fileContent = array.array('d')
    with open(fileName, mode='rb') as file:
        fileContent.fromfile(file)
    return fileContent

这是作为原始机器值的 C 级读取。 mmap.mmap 也可以通过创建 memoryviewmmap 对象并将其强制转换来工作。

【讨论】:

  • 我现在试试。
  • 我收到这条消息:'array.array' 没有属性'array'
  • 那是因为我的导入中有“从数组导入数组”;当我改为“导入数组”时,问题就解决了。
  • @RTC222:是的,我不喜欢“模块并且其中的唯一类共享相同名称”的东西。在现代 Python 中,他们可能会将类命名为 Array(与 PEP8 匹配非内置插件,例如 collections.OrderedDict),但我们永远被遗留名称所困扰,哇!
  • 我也不喜欢这样,因为它令人困惑。我也更喜欢导入整个模块,而不仅仅是一个类(例如 from xxx import yyy)。
猜你喜欢
  • 2019-10-02
  • 2011-01-24
  • 2019-09-12
  • 2013-04-07
  • 2015-03-27
  • 1970-01-01
  • 2014-11-03
  • 2012-05-01
相关资源
最近更新 更多