Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stop having carriage returns added to my file output in Python?

Tags:

python

file-io

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.

like image 489
Alex Mao Avatar asked Jan 19 '23 22:01

Alex Mao


2 Answers

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.

like image 193
Jeremy Avatar answered Feb 02 '23 01:02

Jeremy


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

like image 23
Baltasarq Avatar answered Feb 02 '23 00:02

Baltasarq