Python - Only last line is saved to file

后端 未结 4 563
我寻月下人不归
我寻月下人不归 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 01:52

    you need to write

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

    This will append the file, rather than write over whatever else you put in it.

    0 讨论(0)
  • 2020-12-02 01:54

    Did you try with parameter 'a' So: f = open("output.txt", "a")

    That will open the file with pointer at the end. http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python

    0 讨论(0)
  • 2020-12-02 02:05

    In every iteration you are opening the file, erasing its content, writing and closing. It is much better to open it only once:

    f = open('output.txt', 'w')
    # do loop
        f.write(stuff)
    f.close()
    

    Or, much better:

    with open('output.txt', 'w') as f:
        while loop:
           f.write(stuff)
    

    This method is not only cleaner, but also performs much better, as you can cache the contents of the file, and use the minimal number of OS calls.

    0 讨论(0)
  • 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.

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