Python get proper line ending

ぃ、小莉子 提交于 2019-11-26 22:44:56

问题


Is there an easy way to get the type of line ending that the current operating system uses?


回答1:


If you are operating on a file that you opened in text mode, then you are correct that line breaks all show up as '\n'. Otherwise, you are looking for os.linesep .

From http://docs.python.org/library/os.html:

os.linesep

The string used to separate (or, rather, terminate) lines on the current platform. This may be a single character, such as '\n' for POSIX, or multiple characters, for example, '\r\n' for Windows. Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.




回答2:


Oh, I figured it out. Apparently, PEP-278 states the following:

Any line ending in the input file will be seen as a '\n' in Python, so little other code has to change to handle universal newlines.




回答3:


If specify test resp. binary properly when opening files, and use universal newlines, you shouldn't have to worry about different newlines most of the time.

But if you have to, use os.linesep




回答4:


os.linesep is important as it depends (as the name implied:)) on os.

E.g. on Windows, it is not "\n" but rather "\r\n".

But if you don't care about multi-platform stuff you can just use '\n'.



来源:https://stackoverflow.com/questions/454725/python-get-proper-line-ending

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