Correct way to write line to file?

后端 未结 14 1928
日久生厌
日久生厌 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:40

    This should be as simple as:

    with open('somefile.txt', 'a') as the_file:
        the_file.write('Hello\n')
    

    From The Documentation:

    Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.

    Some useful reading:

    • The with statement
    • open()
      • 'a' is for append, or use
      • 'w' to write with truncation
    • os (particularly os.linesep)

提交回复
热议问题