How to remove ^M

DGT picture DGT · Jul 7, 2010 · Viewed 25.7k times · Source

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)

Answer

Chris B. picture Chris B. · Jul 7, 2010

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.