Is there a way to keep multiple lines when printing to a .txt file in python?

Viewed 52

The original code looks like this:

for i in top_k:
   print(template.format(labels[i], results[i]))

I modified the code to this:

for i in top_k:
    outputFile = open('output.txt', 'w')
    print(template.format(labels[i], results[i]), file = outputFile)
    outputFile.close()

The original code works great since it's printing line by line in the console. But the modified code only prints the last to come from the loop to a .txt file. From what I can tell, it's replacing the text each time the loop runs, so the first text is replaced with the second text, and so forth.

3 Answers

Use 'a' as the argument to open instead of 'w'. It appends rather than overwrites the file.

The solution is using a mode to append the file.

outputFile = open('output.txt', 'a')
for i in top_k:
    print(template.format(labels[i], results[i]), file = outputFile)
outputFile.close()

However, I would recommend you to use pythonic way to append the file line by line using with.

with open("output.txt", "a") as outputFile :
    for i in top_k:
        outputFile.write(template.format(labels[i], results[i]), "\n")

You are opening your file with w mode which opens and "truncates" the file first, as you can see from the docs for the builtin open. This means that it starts writing from the start of the file rather than the end. If you want to "append" the text, you should use a instead.

outputFile = open('output.txt', 'a')

Additionally you do not want to be opening and closing the file for each iteration, as that task can be expensive and cause a hit to performance. I'd suggest using with to manage the file context.

with open('output.txt', a):
    for i in top_k:
        print(template.format(labels[i], results[i]), file = outputFile)
Related