簡體   English   中英

在Python中讀取和解釋二進制文件中的數據

[英]Reading and interpreting data from a binary file in Python

我想逐字節讀取文件並檢查每個字節的最后一位是否設置:

#!/usr/bin/python

def main():
    fh = open('/tmp/test.txt', 'rb')
    try:
        byte = fh.read(1)
        while byte != "":
            if (int(byte,16) & 0x01) is 0x01:
                print 1
            else:
                print 0
            byte = fh.read(1)
    finally:
        fh.close

    fh.close()

if __name__ == "__main__":
        main()

我得到的錯誤是:

Traceback (most recent call last):
  File "./mini_01.py", line 21, in <module>
    main()
  File "./mini_01.py", line 10, in main
    if (int(byte,16) & 0x01) is 0x01:
ValueError: invalid literal for int() with base 16: '\xaf'

有人有想法嗎? 我沒有成功使用struct和binascii模塊。

嘗試使用bytearray類型(Python 2.6及更高版本),它更適合處理字節數據。 你的try塊只是:

ba = bytearray(fh.read())
for byte in ba:
    print byte & 1

或者創建結果列表:

low_bit_list = [byte & 1 for byte in bytearray(fh.read())]

這是有效的,因為當您索引一個bytearray您只需返回一個整數(0-255),而如果您只是從文件中讀取一個字節,則會返回一個字符串,因此需要使用ord將其轉換為整數。


如果你的文件太大而不能舒服地保存在內存中(雖然我猜它不是),那么可以使用mmap從緩沖區創建bytearray

import mmap
m = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ)
ba = bytearray(m)

您想使用ord而不是int

if (ord(byte) & 0x01) == 0x01:

單程:

import array

filebytes= array.array('B')
filebytes.fromfile(open("/tmp/test.txt", "rb"))
if all(i & 1 for i in filebytes):
    # all file bytes are odd

其他方式:

fobj= open("/tmp/test.txt", "rb")

try:
    import functools
except ImportError:
    bytereader= lambda: fobj.read(1)
else:
    bytereader= functools.partial(fobj.read, 1)

if all(ord(byte) & 1 for byte in iter(bytereader, '')):
    # all bytes are odd
fobj.close()

暫無
暫無

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

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