Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

Add Hex characters in a file with python

I would like to add a list of specific Hex characters at the first line of my file.

bin = "420d0d0a010000000000000000000000"

file1:

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
...

file2:

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
...

I would like to get the file2.

I tried that:

bin = "420d0d0a010000000000000000000000"

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

    lines[0] = f"{bin}
"

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

But it didn't work, I had this error:

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

Maybe it's not the right thing to do?

Thanks in advance, have a good day.

question from:https://stackoverflow.com/questions/66056853/add-hex-characters-in-a-file-with-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to open your files in binary mode and to convert the hex str to bytes using bytes.fromhex.

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...