Search code examples
python-3.xwindowshexnewline

Python how to write in binary mode a list of hexadecimals?


I have a string of hex representations of text that I need to write to a file.

toWrite = "020203480A"

with open("example.bin", "w") as file:
   file.write(chr(int(toWrite, 16)))

The problem is that whenever I write LF (0A) Windows automatically adds CR (0D). I know because I open the file in HxD I read 02 02 03 48 0D 0A.

How do I prevent Windows from adding CR before LF?


Solution

  • If you want to directly write bytes to a file without localized line ending behavior, open the file in binary mode instead of text mode:

    toWrite = "020203480A"
    
    # Note "wb" instead of "w"
    with open("example.bin", "wb") as file:
       file.write(bytes.fromhex(toWrite))
    

    or, using pathlib to automatically handle opening and closing the file:

    from pathlib import Path
    
    toWrite = "020203480A"
    p = Path("example.bin")
    p.write_bytes(bytes.fromhex(toWrite))