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

后端 未结 5 1891
野性不改
野性不改 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:18

    You could write a function that converts text then writes it. For example:

    def DOSwrite(f, text):
        t2 = text.replace('\n', '\r\n')
        f.write(t2)
    #example
    f = open('/path/to/file')
    DOSwrite(f, "line 1\nline 2")
    f.close()
    

提交回复
热议问题