How to modify a text file?

前端 未结 8 1505
不思量自难忘°
不思量自难忘° 2020-11-22 03:14

I\'m using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 04:03

    Depends on what you want to do. To append you can open it with "a":

     with open("foo.txt", "a") as f:
         f.write("new line\n")
    

    If you want to preprend something you have to read from the file first:

    with open("foo.txt", "r+") as f:
         old = f.read() # read everything in the file
         f.seek(0) # rewind
         f.write("new line\n" + old) # write the new line before
    

提交回复
热议问题