0

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}\n"

    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.

6
  • Edit the question to explain "didn't work". Commented Feb 5, 2021 at 2:46
  • But precisely, I don't know why it didn't work, that's also why I'm asking for help. Commented Feb 5, 2021 at 2:51
  • 1
    Is this a hexdump or the actual file content? Also, please include the full traceback of the error. Commented Feb 5, 2021 at 2:55
  • Hex dump I think, I'm trying to modify a .pyc file Commented Feb 5, 2021 at 2:58
  • you probably need to open the file as binary, but it's difficult to know exactly what's wrong Commented Feb 5, 2021 at 3:02

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

WOW, IT WORKS, thank you very much, thank you for taking the time to help me. Have a good day ! <3
0

The problem is you are replacing the first line for your new line, but you need to append the new line to the beginning.

Just try replacing this line

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

For this

lines.insert(0,bin)

1 Comment

Hi, thanks for your answer, but I got the same error:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.