使用 python 在文件中添加十六进制字符

Add Hex characters in a file with python

我想在文件的第一行添加特定十六进制字符的列表。

bin = "420d0d0a010000000000000000000000"

文件 1:

e300 0000 0000 0000 0000 0000 0002 0000
0040 0000 0073 6a00 0000 6400 6401 6c00
5a00 6400 6401 6c01 5a01 6400 6401 6c02
5a02 6400 6401 6c03 5a03 6400 6401 6c02
...

文件 2:

420d 0d0a 0100 0000 0000 0000 0000 0000
e300 0000 0000 0000 0000 0000 0002 0000
0040 0000 0073 6a00 0000 6400 6401 6c00
5a00 6400 6401 6c01 5a01 6400 6401 6c02
5a02 6400 6401 6c03 5a03 6400 6401 6c02
...

我要获取文件2。

我试过了:

bin = "420d0d0a010000000000000000000000"

def change_hex():
    with open("file.txt") as f: 
        lines = f.readlines()

    lines[0] = f"{bin}\n"

    with open("file.txt", "w") as f:
        f.writelines(lines)

但是它没有用,我有这个错误:

UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 174: character maps to <undefined>

也许这不是正确的做法?

提前致谢,祝您愉快。

问题是您正在替换新行的第一行,但您需要追加新行到开头.

只需尝试替换此行

lines[0] = f"{bin}\n"

为此

lines.insert(0,bin)

您需要以二进制模式打开文件并使用 bytes.fromhex.

将十六进制 str 转换为字节
header = bytes.fromhex("420d0d0a010000000000000000000000")

def change_hex():
    with open("file.txt", "rb") as f: 
        content = f.read()

    with open("file.txt", "wb") as f:
        f.write(header)
        f.write(content)