python读写二进制文件的方法
本篇章节讲解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,c (12345,67.890000000000001,15) >>> print a,c 12345 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 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”. 希望本文所述对大家的Python程序设计有所帮助。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |