12
votes

How can I remove the ^M character from a text file (at the end of line) in a Python script?

I did the following, and there are ^M at every line-break.

file = open(filename, "w")
file.write(something)
6
Can you post more off your code?. Dont`t know where ^M comes from. New line character make and "\n" not "^M" Remeber to close "file.close()" Dont use file is an reserved word in python use my_file or something. - snippsat
@snippsat ^M is the terminal character escape which is written as '\n' in C syntax - Pete Kirkham
@Ned you're right - I was thinking of the old days where if you typed Ctrl+M you get a new line, but that's because it's carriage return not newline - Pete Kirkham

6 Answers

9
votes

If you're writing the file, you should specify open(filename, "wb"). That way, you'll be writing in binary mode, and Python won't attempt to determine the correct newlines for the system you're on.

6
votes

Python can open a file in binary mode or in text mode. Text is the default, so a mode of "w" means write in text mode. In text mode, Python will adjust the line endings for the platform you're on. This means on Windows, this code:

f = open("foo.txt", "w")
f.write("Hello\n")

will result in a text file containing "Hello\r\n".

You can open the file in binary mode by using "b" in the mode:

f = open("foo.txt", "wb")
f.write("Hello\n")

results in a text file containing "Hello\n".

4
votes

string.replace('\r', '') worked for me.

Ugly, but nor r+ nor r+b nor NOTHING ELSE worked (for me, sure) :(

2
votes

dos2unix filename.py

to convert the line breaks to UNIX style.

1
votes

For portability, you can try the following

import os
file = open(filename, "w")
file.write(something.replace('\r\n', os.linesep))
-1
votes

run autopep8 on the file

> apt-get install python-autopep8

> autopep8 python_file_name > new_python_file_name.py