简体   繁体   English

Python - 如何逐字节编辑十六进制文件

[英]Python - How to edit hexadecimal file byte by byte

I want to be able to open up an image file and extra the hexadecimal values byte-by-byte. 我希望能够逐字节地打开图像文件并添加十六进制值。 I have no idea how to do this and googling "python byte editing" and "python byte array" didn't come up with anything, surprisingly. 我不知道如何做到这一点和google搜索“python字节编辑”和“python字节数组”没有提出任何东西,令人惊讶。 Can someone point me towards the library i need to use, specific methods i can google, or tutorials/guides? 有人能指出我需要使用的库,我可以谷歌的特定方法,或教程/指南?

Depending on what you want to do it might be enough to open the file in binary mode and read the data with the normal file functions: 根据您的要求,可能足以以二进制模式打开文件并使用普通文件函数读取数据:

# load it
with open("somefile", 'rb') as f:
    data = f.read()

# do something with data
data.reverse()

# save it
with open("somefile.new", 'wb') as f:
    f.write(data)

Python doesn't really care if the data string contains "binary" or "text" data. Python并不关心data字符串是否包含“二进制”或“文本”数据。 If you just want to do simple modifications to a file of reasonable size this is probably good enough. 如果您只想对合理大小的文件进行简单修改,这可能就足够了。

Python standard library has mmap module, which can be used to do exactly this. Python标准库有mmap模块,可用于完成此操作。 Take a look on the documentation for further information. 查看文档以获取更多信息。

The Hachoir framework is a set of Python library and tools to parse and edit binary files: Hachoir框架是一组用于解析和编辑二进制文件的Python库和工具:

http://pypi.python.org/pypi/hachoir-core http://pypi.python.org/pypi/hachoir-core

It has knowledge of common file types, so this could just be what you need. 它具有常见文件类型的知识,因此这可能就是您所需要的。

Check out the stuct module. 查看stuct模块。

This module performs conversions between Python values and C structs represented as Python strings. 此模块执行Python值和表示为Python字符串的C结构之间的转换。 It uses format strings (explained below) as compact descriptions of the lay-out of the C structs and the intended conversion to/from Python values. 它使用格式字符串(如下所述)作为C结构布局的简要描述以及与Python值的预期转换。 This can be used in handling binary data stored in files or from network connections, among other sources. 这可用于处理存储在文件中的二进制数据或来自网络连接以及其他来源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM