日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

python读写二进制文件的方法

發(fā)布時(shí)間:2025/4/5 python 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python读写二进制文件的方法 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

本文實(shí)例講述了python讀寫(xiě)二進(jìn)制文件的方法。分享給大家供大家參考。具體如下:

初學(xué)python,現(xiàn)在要讀一個(gè)二進(jìn)制文件,查找doc只發(fā)現(xiàn) file提供了一個(gè)read和write函數(shù),而且讀寫(xiě)的都是字符串,如果只是讀寫(xiě)char等一個(gè)字節(jié)的還行,要想讀寫(xiě)如int,double等多字節(jié)數(shù) 據(jù)就不方便了。在網(wǎng)上查到一篇貼子,使用struct模塊里面的pack和unpack函數(shù)進(jìn)行讀寫(xiě)。下面就自己寫(xiě)代碼驗(yàn)證一下。

?
1234>>> from struct import *>>> file = open(r"c:/debug.txt", "wb")>>> file.write(pack("idh", 12345, 67.89, 15))>>> file.close()

接著再將其讀進(jìn)來(lái)

?
1234567>>> 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,c12345 67.89 15>>> file.close()

在操作過(guò)程中需要注意數(shù)據(jù)的size

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

方法1:

?
1234myfile=open('c:\\t','rb')s=myfile.read(1)byte=ord(s) #將一個(gè)字節(jié) 讀成一個(gè)數(shù)print hex(byte) #轉(zhuǎn)換成16進(jìn)制的字符串

方法2

?
1234import structmyfile=open('c:\\t','rb').read(1)print struct.unpack('c',myfile)print struct.unpack('b',myfile)

寫(xiě)入

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()

希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。

《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀

總結(jié)

以上是生活随笔為你收集整理的python读写二进制文件的方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。