Correct way to write line to file?

后端 未结 14 1896
日久生厌
日久生厌 2020-11-21 06:27

I\'m used to doing print >>f, \"hi there\"

However, it seems that print >> is getting deprecated. What is the recommended way t

14条回答
  •  名媛妹妹
    2020-11-21 06:51

    If you want to avoid using write() or writelines() and joining the strings with a newline yourself, you can pass all of your lines to print(), and the newline delimiter and your file handle as keyword arguments. This snippet assumes your strings do not have trailing newlines.

    print(line1, line2, sep="\n", file=f)
    

    You don't need to put a special newline character is needed at the end, because print() does that for you.

    If you have an arbitrary number of lines in a list, you can use list expansion to pass them all to print().

    lines = ["The Quick Brown Fox", "Lorem Ipsum"]
    print(*lines, sep="\n", file=f)
    

    It is OK to use "\n" as the separator on Windows, because print() will also automatically convert it to a Windows CRLF newline ("\r\n").

提交回复
热议问题