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
you need to write
f = open("output.txt", "a")
This will append the file, rather than write over whatever else you put in it.
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
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.
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.