How to convert CRLF to LF on a Windows machine in Python

前端 未结 4 925
我寻月下人不归
我寻月下人不归 2020-12-14 20:20

So I got those template, they are all ending in LF and I can fill some terms inside with format and still get LF files by opening with "wb"

Those templates

4条回答
  •  遥遥无期
    2020-12-14 21:07

    Python's open function supports the 'rU' mode for universal newlines, in which case it doesn't mind which sort of newline each line has. In Python 3 you can also request a specific form of newline with the newline argument for open.

    Translating from one form to the other is thus rather simple in Python:

    with open('filename.in', 'rU') as infile,                 \
       open('filename.out', 'w', newline='\n') as outfile:
           outfile.writelines(infile.readlines())
    

    (Due to the newline argument, the U is actually deprecated in Python 3; the equivalent form is newline=None.)

提交回复
热议问题