tags:

views:

138

answers:

3

How can I remove the ^M character from a text file (at the end of line) in Python script? I did the following, and there are ^M at every line-break. Please help.

file = open(filename, "w")
file.write(something)

Thanks in advance.

+3  A: 

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.

Chris B.
Thanks for your reply, but I'm trying to write 'something' to 'file' and it seems 'Universal newline mode' can only be used with 'rU', if I'm not mistaken. It doesn't work for me, anyways.
DGT
+2  A: 

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".

Ned Batchelder
Actually, that 'something' comes from html form textarea, where I copy and paste 'something'. The script then gets the value:<code>something = form["some_name"].value </code>
DGT
A: 

dos2unix filename.py

to convert the line breaks to UNIX style.

bigredbob