Correct way to write line to file?

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

    When you said Line it means some serialized characters which are ended to '\n' characters. Line should be last at some point so we should consider '\n' at the end of each line. Here is solution:

    with open('YOURFILE.txt', 'a') as the_file:
        the_file.write("Hello")
    

    in append mode after each write the cursor move to new line, if you want to use w mode you should add \n characters at the end of the write() function:

    the_file.write("Hello\n")
    

提交回复
热议问题