how to add lines to existing file using python

前端 未结 3 1610

I already created a txt file using python with a few lines of text that will be read by a simple program. However, I am having some trouble reopening the file and writing ad

相关标签:
3条回答
  • 2020-12-03 02:59

    Open the file for 'append' rather than 'write'.

    with open('file.txt', 'a') as file:
        file.write('input')
    
    0 讨论(0)
  • 2020-12-03 03:10

    Use 'a', 'a' means append. Anything written to a file opened with 'a' attribute is written at the end of the file.

    with open('file.txt', 'a') as file:
        file.write('input')
    
    0 讨论(0)
  • 2020-12-03 03:17

    If you want to append to the file, open it with 'a'. If you want to seek through the file to find the place where you should insert the line, use 'r+'. (docs)

    0 讨论(0)
提交回复
热议问题