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

后端 未结 1 1242
长情又很酷
长情又很酷 2021-02-13 23:02

If taken into consideration that carriage return = \\r and line feed = \\n

Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [M         


        
1条回答
  •  醉梦人生
    2021-02-13 23:39

    You can do this by passing '' to the newline parameter when opening the text file.

    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()
    

    As described in the 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.

    The default value for newline is None, by specifiying '', you're forcing Python to write the newline (\n or \r) without translating it.

    0 讨论(0)
提交回复
热议问题