簡體   English   中英

用 Python 讀取大型二進制文件的最快方法

[英]Fastest way to read a large binary file with Python

我需要在 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 一樣。

您可以使用array.array('d')fromfile方法:

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也可以通過創建mmap對象的memoryview並投射它來工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM