Ziamor
Ziamor

Reputation: 533

Stop python from writing a carriage return when hex value is 0x0A

I decided to brush up on my python, and for the first project I thought I would write a script to help me with some homework for another class I have. For this class, I have an excel spread sheet that converts some data to hex. I would normally have to manually type out the hex values into the program I'm using or I could load the binary data from a file.

The script I have set up right now lets me copy the section in the spread sheet and copy the contents to a temporary text file. When I run my script it creates a file with the binary data. It works except for when I have a hex value of 0x0A, because of the way I convert the string value to hex converts it to '\n' so the binary file has 0D 0A rather then just 0A.

The way I get the hex value:

hexvalue = chr(int(string_value,16))

The way I write to the file:

f = file("code_out", "w")
for byte in data:
    f.write(byte)
f.close()

What's the proper way of doing this?

Upvotes: 1

Views: 5294

Answers (2)

user2864740
user2864740

Reputation: 61935

Open the file in "binary mode"

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written.

That is, under non-"binary mode" in Windows, when a "\n" (LF, \x0A) is written to the file stream the actual result is that the byte sequence "\r\n" (CR LF, \x0D \x0A) is written. See newline for additional notes.

This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

Upvotes: 2

michaelb
michaelb

Reputation: 747

I think you need to open the file for binary writing!

f = open('file', 'wb')

Upvotes: 4

Related Questions