首頁 >後端開發 >Python教學 >如何迭代 Python 二進位檔案中的位元組?

如何迭代 Python 二進位檔案中的位元組?

Linda Hamilton
Linda Hamilton原創
2024-12-08 13:19:11928瀏覽

How Can I Iterate Through Bytes in a Python Binary File?

在Python 中迭代二進位檔案中的位元組

要在Python 中讀取二進位檔案並對該檔案中的每個檔案位元組執行操作,採用以下技術:

Python >= 3.8

利用海象運算子(=) 取得有效的解:

with open("myfile", "rb") as f:
    while (byte := f.read(1)):
        # Perform actions on the byte

Python >= 3

舊的Python 3版本,採用稍微詳細一點的方法:

with open("myfile", "rb") as f:
    byte = f.read(1)
    while byte != b"":
        # Perform actions on the byte
        byte = f.read(1)

Python >= 2.5

在Python 2 中,擷取原始字元而不是位元組物件:

with open("myfile", "rb") as f:
    byte = f.read(1)
    while byte != "":
        # Perform actions on the byte
        byte = f.read(1)

Python 2.4及更早版本

使用舊版本,以下方法:

f = open("myfile", "rb")
try:
    byte = f.read(1)
    while byte != "":
        # Perform actions on the byte
        byte = f.read(1)
finally:
    f.close()

以上是如何迭代 Python 二進位檔案中的位元組?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn