激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

腳本之家,腳本語言編程技術及教程分享平臺!
分類導航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服務器之家 - 腳本之家 - Python - python讀寫二進制文件的方法

python讀寫二進制文件的方法

2020-06-26 12:44守株待兔 Python

這篇文章主要介紹了python讀寫二進制文件的方法,實例分析了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程序設計有所幫助。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 欧美成年性h版影视中文字幕 | 强伦女教师视频 | 欧美一级高清免费 | 亚洲射情| 99精品国产一区二区三区 | av免费在线免费观看 | 国产精品久久久久久久久岛 | 国产在线观看一区二区三区 | 萌白酱福利视频在线网站 | 久久久免费电影 | 特级黄aaaaaaaaa毛片 | 免费在线性爱视频 | 欧美一级视频在线 | 国产免费最爽的乱淫视频a 毛片国产 | 欧美激情猛片xxxⅹ大3 | 91在线视频精品 | 福利片在线看 | 久久aⅴ国产欧美74aaa | 精品国产乱码一区二区三区四区 | 久国产 | 国产精品爱久久久久久久 | 国产日韩中文字幕 | 精品一二三区视频 | 九一免费国产 | 一级毛片免费电影 | 久草在线资源视频 | 久久av热 | 精选久久 | 亚洲3atv精品一区二区三区 | 91久久国产露脸精品免费 | 成人在线视频精品 | 精品欧美一区二区精品久久 | 亚洲一级簧片 | 国产精品成人亚洲一区二区 | 久久欧美亚洲另类专区91大神 | 成人午夜在线观看视频 | 黑人一区二区三区四区五区 | 91天堂国产在线 | 久久亚洲成人 | 96视频在线免费观看 | a一级黄色毛片 |