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随手笔记第一篇(2)之初识列表和元组

Python随手笔记第一篇(2)之初识列表和元组

Python中,列表和元组是一种数据结构:序列,序列中的每个元素都被分配一个序号,元素的位置,第一原元素的位置为0,因此类推。序列是最基本的数据结构,列表和元组他们之间具有一定的区别,即...

Django 中间键和上下文处理器的使用

Django 中间键和上下文处理器的使用

一、中间键的引入: Django中间件(Middleware)是一个 轻量级、底层的 “插件”系 统,可以介入 Django的请求和响应处理过程, 修改 Django的输入或输出. dj...

Python3 Tkinkter + SQLite实现登录和注册界面

Python3 Tkinkter + SQLite实现登录和注册界面

本文实例为大家分享了Python3 Tkinkter + SQLite 实现登录和注册界面,供大家参考,具体内容如下 Ubuntu14 + Python3.4 + Pycharm2018...

Python multiprocess pool模块报错pickling error问题解决方法分析

本文实例讲述了Python multiprocess pool模块报错pickling error问题解决方法。分享给大家供大家参考,具体如下: 问题 之前在调用class内的函数用mu...

基于Python的PIL库学习详解

摘要 对于图像识别,大量的工作在于图像的处理,处理效果好,那么才能很好地识别,因此,良好的图像处理是识别的基础。在Python中,有一个优秀的图像处理框架,就是PIL库,本博文会分模块...