定义二进制文件的结构然后读或写的库。
binaryfile的Python项目详细描述
二进制文件
定义二进制文件的结构然后读或写的库。在
importbinaryfiledefpng(b):b.byteorder='big'b.skip(16)b.uint('width',4)b.uint('height',4)b.uint('depth',1)withopen('image.png','rb')asfh:data=binaryfile.read(fh,png)print(f"Image is {data.width} pixels wide, {data.height} pixels tall, and {data.depth} bits deep.")
入门
要求
您将需要Python3.6或更高版本。在
安装
带有Python启动器的Windows:
^{pr2}$带Pithon3的python3:
pip3 install binaryfile
如何使用
如果要读或写二进制文件,首先需要定义文件结构。为此,您可以编写一个接受单个参数的函数,它是binaryfile.fileformat.BinarySectionBase. 然后通过对所述参数调用方法来定义文件结构:
importbinaryfileimportio# Define the file structuredeffile_spec(f):size=f.count('size','text',2)# A two-byte unsigned integerf.bytes('text',size)# A variable number of bytesif__name__=='__main__':# Read the file and print the text fieldwithopen('myfile.dat','rb')asfile_handle:data=binaryfile.read(file_handle,file_spec)print(data.text.decode('utf-8'))# Modify the text fielddata.text+=' More Text!'.encode('utf-8')# Errors will throw exceptions and# cause the written file to be truncated,# so write to a memory buffer firstmodified_buffer=io.BytesIO()binaryfile.write(modified_buffer,data,file_spec)# Then write back to filewithopen('myfile.dat','wb')asfile_handle:file_handle.write(modified_buffer.getvalue())
您可以将定义分解为可重用的部分:
defsubsection_spec(f):f.struct('position','fff')# Three floats, using a format string from Python's built-in struct moduledefsection_spec(f):f.int('type',1)# A one-byte signed integerf.section('subsection1',subsection_spec)# Three floats, as specified in subsection_specf.section('subsection2',subsection_spec)deffile_spec(f):f.section(f'section1',section_spec)f.section(f'section2',section_spec)f.section(f'section3',section_spec)if__name__=='__main__':withopen('myfile2.dat','rb')asfile_handle:data=binaryfile.read(file_handle,file_spec)print(data.section2.subsection1.position)
您可以将字段声明为数组并使用循环:
deffile_spec(f):f.array('positions')# Declare "positions" to be an arraycount=f.count('count','positions',4)foriinrange(count):f.struct('positions','fff')# Each time "positions" is used, it's the next element of the array
配置
结果类型
默认情况下,一个文件被读入binaryfile.utils.SimpleDict
,它允许您用点表示法访问字段(例如foo.bar.baz
)。这意味着您不能在Python中使用无效字段名的名称。在
要重写结果类型,请将所需的类型传递给read调用中的result_type
,例如:
binaryfile.read(fh,spec,result_type=dict)
所需的类型必须是实现__getitem__
、__setitem__
和__contains__
的类dict类型。在
字节顺序
默认的字节顺序是big-endian。您可以通过在BinarySectionBase
对象上设置byteorder
或在支持它的单个方法中设置byteorder
。
有效的字节顺序是'big'和'little',这也是sys.byteorder
返回的可能值。在
defspec(b):b.byteorder='little'b.int('a',4)# Little-endianb.int('b',4,byteorder='big')# Big-endianb.int('c',4)# Little-endian again
自动测试
设置环境
- 创建并激活Python virtual environment。在
- 在项目根目录下,运行
./setup.py develop
将链接到项目源的二进制文件包安装到venv中。在
运行测试
确保venv处于活动状态,然后运行tests
文件夹中的Python文件。在
许可证
这个项目是在MIT许可下授权的,详细信息请参见LICENSE。在
- 项目
标签: