国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python讀寫二進制文件的方法

2020-02-23 01:09:00
字體:
來源:轉載
供稿:網友

本文實例講述了python讀寫二進制文件的方法。分享給大家供大家參考。具體如下:

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

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

接著再將其讀進來

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

在操作過程中需要注意數據的size

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

方法1:

myfile=open('c://t','rb')s=myfile.read(1)byte=ord(s) #將一個字節 讀成一個數print hex(byte) #轉換成16進制的字符串

方法2

import structmyfile=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程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 潞城市| 鹿邑县| 仁化县| 大邑县| 安远县| 长寿区| 临江市| 湟中县| 鄄城县| 玉林市| 内丘县| 额济纳旗| 天柱县| 虎林市| 银川市| 璧山县| 嵊州市| 迁西县| 伽师县| 阿勒泰市| 镇坪县| 富平县| 辽宁省| 宜春市| 河北区| 景德镇市| 精河县| 泰兴市| 星子县| 龙川县| 都江堰市| 克拉玛依市| 临夏市| 渭南市| 兴仁县| 康乐县| 昌平区| 宿州市| 阿勒泰市| 法库县| 灵石县|