Python - Only last line is saved to file

后端 未结 4 572
我寻月下人不归
我寻月下人不归 2020-12-02 01:18

I\'m trying to output the result of my script into a text file. The script is working fine, the only problem is when results are saved into the text file (output.txt), only

4条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-02 02:09

    I'm going to take a wild guess and assume that all of this code happens inside a loop. Each time through the loop, you write one more line, but at the end, you only have the last line.

    If that's the problem, here's the issue:

            f = open("output.txt", "w")              
    

    When you open a file in 'w' mode, that truncates any existing file.

    To fix this, either open the file once, outside the loop, instead of over and over again, or open it in 'a' mode or 'r+' mode or some other mode that doesn't truncate the file.

    The documentation for the open function, or the inline help in the interactive interpreter, explains what all the different modes mean.

提交回复
热议问题