^M characters in exported file, converting to newlines

為{幸葍}努か 提交于 2021-01-27 07:00:50

问题


I exported a CSV from excel to parse using python. When I opened the vimmed the CSV, I noticed that it was all one line with ^M characters where newlines should be.

Name, Value, Value2, OtherStuff ^M Name, Value, Value2, OtherStuff ^M

I have the file parsed such that I modify the values and put the into a string (using 'rU' mode in csvreader). However, the string has no newlines. So I am wondering, is there a way to split the string on this ^M character, or a way to replace it with a \n?


回答1:


^M is how vim displays windows end-of-line's

The dos2unix command should fix those up for you:

dos2unix my_file.csv

It's due to the different EOL formats on Windows/Unix.

On windows, it's \r\n

On Unix/Linux/Mac, it's just \n

The ^M is actually vim showing you the windows CR (Carriage Return) or \r

The python open command documentation has more information on handling Universal Newlines: http://docs.python.org/2/library/functions.html#open




回答2:


If you are on a unix system, there is a program called dos2unix (and its counterpart unix2dos) that will do exactly that conversion.

But, it is pretty much the same as something like this:

sed -i -e 's/$/\r/' file


来源:https://stackoverflow.com/questions/17752460/m-characters-in-exported-file-converting-to-newlines

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