python讀寫二進位檔案的方法

來源:互聯網
上載者:User

python讀寫二進位檔案的方法

   本文執行個體講述了python讀寫二進位檔案的方法。分享給大家供大家參考。具體如下:

  初學python,現在要讀一個二進位檔案,尋找doc只發現 file提供了一個read和write函數,而且讀寫的都是字串,如果只是讀寫char等一個位元組的還行,要想讀寫如int,double等多位元組數 據就不方便了。在網上查到一篇貼子,使用struct模組裡面的pack和unpack函數進行讀寫。下面就自己寫代碼驗證一下。

  ?

1

2

3

4

>>> from struct import *

>>> file = open(r"c:/debug.txt", "wb")

>>> file.write(pack("idh", 12345, 67.89, 15))

>>> file.close()

  接著再將其讀進來

  ?

1

2

3

4

5

6

7

>>> file = open(r"c:/debug.txt", "rb")

>>> (a,b,c) = unpack("idh",file.read(8+8+2))

>>> a,b,c

(12345, 67.890000000000001, 15)

>>> print a,b,c

12345 67.89 15

>>> file.close()

  在操作過程中需要注意資料的size

  注意 wb,rb中的b字,一定不可以少

  方法1:

  ?

1

2

3

4

myfile=open('c:\\t','rb')

s=myfile.read(1)

byte=ord(s) #將一個位元組 讀成一個數

print hex(byte) #轉換成16進位的字串

  方法2

  ?

1

2

3

4

import struct

myfile=open('c:\\t','rb').read(1)

print struct.unpack('c',myfile)

print struct.unpack('b',myfile)

  寫入

  To open a file for binary writing is easy, it is the same way you do for reading, just change the mode into “wb”.

  file = open("test.bin","wb")

  But, how to write the binary byte into the file?

  You may write it straight away with hex code like this:

  file.write("\x5F\x9D\x3E") file.close()

  Now, check it out with hexedit,

  hexedit test.bin

  You will see this:

  00000000 5F 9D 3E _.> 00000020 00000040

  Now, open the file to append more bytes:

  file = open("test.bin","ab")

  What if I want to store by bin value into a stream and write it one short?

  s ="\x45\xF3" s = s + "%c%c" % (0x45,0xF3) file.write(s) file.close()

  Any convenient ways if I can obtained a hex string, and want to convert it back to binary format?

  Yes, you just need to import binascii

  import binascii hs="5B7F888489FEDA" hb=binascii.a2b_hex(hs) file.write(hb) file.close()

  希望本文所述對大家的Python程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.