How to remove ^M

陌路散爱 提交于 2019-11-29 10:01:13

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.

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

dos2unix filename.py

to convert the line breaks to UNIX style.

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

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

For portability, you can try the following

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

run autopep8 on the file

> apt-get install python-autopep8

> autopep8 python_file_name > new_python_file_name.py
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!