Using python to write text files with DOS line endings on linux

后端 未结 5 1893
野性不改
野性不改 2021-02-18 17:40

I want to write text files with DOS/Windows line endings \'\\r\\n\' using python running on Linux. It seems to me that there must be a better way than manually putting a \'\\r\\

5条回答
  •  青春惊慌失措
    2021-02-18 18:02

    For Python 2.6 and later, the open function in the io module has an optional newline parameter that lets you specify which newlines you want to use.

    For example:

    import io
    with io.open('tmpfile', 'w', newline='\r\n') as f:
        f.write(u'foo\nbar\nbaz\n')
    

    will create a file that contains this:

    foo\r\n
    bar\r\n
    baz\r\n
    

提交回复
热议问题