Writing to file using Python

This question already has an answer here:

  • How do you append to a file? 8 answers

  • You need to change the second flag when opening the file:

  • w for only writing (an existing file with the same name will be erased)
  • a opens the file for appending
  • Your code then should be:

    with open("output.txt", "a") as f:
    

    Every time you enter and exit the with open... block, you're reopening the file. As the other answers mention, you're overwriting the file each time. In addition to switching to an append, it's probably a good idea to swap your with and for loops so you're only opening the file once for each set of writes:

    with open("output.txt", "a") as f:
        for key in atts:
            f.write(key)
    

    我相信你需要以追加模式打开文件(这里回答:附加到Python中的文件),像这样:

    with open("output.txt", "a") as f:
        ## Write out
    
    链接地址: http://www.djcxy.com/p/42402.html

    上一篇: 你如何追加到一个文件?

    下一篇: 使用Python写入文件