转自:https://blog.csdn.net/ShenZhen_zixian/article/details/127806562
数组中数据转换文件为二进制
以下是一个简单的Python脚本,它将数组中的内容读取并将其保存到 test.bin
文件中。
output_path = 'test.bin' # 输出文件的路径和文件名称,这里直接放在工程根目录下,所以没有写绝对路径
# 待写入的数据
li = [0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22]
print(bytes(li))
with open(output_path, 'ab') as f:
f.write(bytes(li))
f.close()
可以借助 hexdump
命令产看生成的二进制文件:
[02:24:53] (*^~^*) ~/workbase/python$ hexdump -C test.bin
00000000 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f |................|
00000010 20 21 22 | !"|
00000013
二进制文件行尾增加内容
test_path = 'test.bin' # 输入文件的路径和文件名称,这里是在工程根目录下,所以没有写绝对路径
# 待插入的数据
li = [0xaa, 0xbb, 0xcc, 0xdd, 0xee]
# 打开并查看原文件
with open(test_path, 'rb') as f:
print(bytes(f.read())) #查看文件内容
# 插入数据
with open(test_path, 'ab+') as f: # ab+: 在文本末尾追加内容
f.write(bytes(li))
f.close()
# 打开并查看插入数据后的文件
with open(test_path, 'rb') as f:
print(bytes(f.read())) #查看文件内容
效果如下:
[02:32:45] (*^~^*) ~/workbase/python$ hexdump -C test.bin
00000000 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f |................|
00000010 20 21 22 aa bb cc dd ee | !".....|
00000018