Skip to content Skip to sidebar Skip to footer

Ignore Newline Character In Binary File With Python?

I open my file like so : f = open('filename.ext', 'rb') # ensure binary reading with b My first line of data looks like this (when using f.readline()): '\x04\x00\x00\x00\x12\x00\x

Solution 1:

(Followed from discussion with OP in chat)

Seems like the file is in binary format and the newlines are just mis-interpreted values. This can happen when writing 10 to the file for example.

This doesn't mean that newline was intended, and it is probably not. You can just ignore it being printed as \n and just use it as data.

Solution 2:

You should just be able to replace the bytes that indicate it is a newline.

>>>d = f.read(4).replace(b'\x0d\x0a', b'') #\r\n should be bytes b'\x0d\x0a'>>>diff = 4 - len(d)>>>while diff > 0: # You can probably make this more sophisticated...    d += f.read(diff).replace(b'\x0d\x0a', b'') #\r\n should be bytes b'\x0d\x0a'...    diff = 4 - len(d)>>>>>>s = struct.unpack("i", d)

This should give you an idea of how it will work. This approach could mess with your data's byte alignment.

If you really are seeing "\n" in your print of d then try .replace(b"\n", b"")

Post a Comment for "Ignore Newline Character In Binary File With Python?"