python读写二进制文件的方法

yipeiwu_com5年前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,b,c
(12345, 67.890000000000001, 15)
>>> print a,b,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”.
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程序设计有所帮助。

相关文章

python中正则表达式的使用方法

本文主要关于python的正则表达式的符号与方法。 findall: 找寻所有匹配,返回所有组合的列表 search: 找寻第一个匹配并返回 sub: 替换符合规律的内容,并返回替换后的...

python如何以表格形式打印输出的方法示例

python如何以表格形式打印输出的方法示例

好久不见,风水轮流转,我竟然写写写python了 近日有个小需求,要求收集统计一些信息上报,并直接在后台控制台打印,写入日志 为了美观,需要以表格形式展现数据,形如 虽说可以用 pre...

python 字段拆分详解

按照固定的字符,拆分已有的字符串 split(sep, n, expand = False) :sep:用于分割的字符串 n:分割为多少列 expand:是否展开为数据框,默认值为Fal...

Python Socket实现简单TCP Server/client功能示例

本文实例讲述了Python Socket实现简单TCP Server/client功能。分享给大家供大家参考,具体如下: 网络上关于socket的介绍文章数不胜数。自己记录下学习的点点滴...

用Python将一个列表分割成小列表的实例讲解

用Python将一个列表分割成小列表的实例讲解

方法一 def list_of_groups(init_list, childern_list_len): ''' init_list为初始化的列表,childern_list_...