I'm trying to parse a BMP file, do some changes and then reassemble a new BMP using Python.
The carriage return seems to be a huge problem. When I open the bitmap file using Notepad++ and search for "\r'
, the character does not exist. I read the file in Python (readData = fileIn.read()) and try searching using readData.find('\r')
it returns -1
. Searching for "\n"
works fine. All is good for now.
When I try to write this exact same block of text into a new BMP using fileOut.write(readData)
and I use Notepad++ to search for "\r"
, I am able to find it (twice, each corresponding to the preexisting "\n"
characters).
Is there a way to write this block of data to a new BMP without "\r"
being added automatically? I've tried applying .strip()
and .replace('\r','')
to the string before writing it to the new file.
You're probably opening the file as text (the default) when you want to open it as binary.
open("example.bmp", "rb") # to [r]ead as [b]inary
open("example.bmp", "wb") # to [w]rite as [b]inary
From the documentation:
The default is to use text mode, which may convert
'\n'
characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append'b'
to the mode value to open the file in binary mode, which will improve portability.
You are opening the file in text mode, while you need binary mode. Find more about open() here: http://docs.python.org/library/functions.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With