用 Python 写换行时避免写回车符 return '\r'

Avoid writing carriage return '\r' when writing line feed with Python

如果考虑到 carriage return = \rline feed = \n

Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> '{:02x}'.format(ord('\n'))
'0a'
>>> '{:02x}'.format(ord('\r'))
'0d'

使用open('filename','w').write('text\n')时如何避免回车return?

在交互模式下你可以这样做:

>>> open('filename','w').write('text\n')
5
>>> for c in open('filename','r').read():
...     print('{:02x}'.format(ord(c)))
...
74
65
78
74
0a

这表示只写了换行符,因此它应该是 5 个字节长。

-rw-r--r-- 1 djuric 197121        6 Jul 15 21:00 filename
                                  ^

实际上是6个字节长。现在这可以是一个 "Windows thing",但是当你在 Notepad++ 中打开文件时,你打开 View > Show Symbols > Show All Characters 你可以看到回车 return那里。

按 CTRL+H 并使用扩展搜索模式将 \r 替换为空后,只剩下换行符。保存文件后,文件中只有换行符,文件长度为5字节。

-rw-r--r-- 1 djuric 197121    5 Jul 15 20:58 filename1
                              ^

那为什么Notepad++可以保存无回车符的换行符return,而python却不能呢?

您可以通过在打开文本文件时将 '' 传递给 newline 参数来实现。

f = open('test.txt', 'w', newline='')
f.write('Only LF\n')
f.write('CR + LF\r\n')
f.write('Only CR\r')
f.write('Nothing')
f.close()

docs所述:

newline controls how universal newlines mode works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:

  • When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.

  • When writing output to the stream, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.

newline 的默认值为 None,通过指定 '',您强制 Python 编写换行符(\n\r) 不翻译。