-2

This code actually overwrite the pre-existing content of out.txt, is there a way to make it print in the next line ?

with open(r'C:\out.txt', "w") as presentList:
    print("Hello", file=presentList)
Wicelo
  • 2,358
  • 2
  • 28
  • 44

2 Answers2

1

Use "a" instead of "w".

This appends new text at the end.

TidB
  • 1,749
  • 1
  • 12
  • 14
0

I think you'll want to open with "r+" instead (opening with "w" overwrites the file!). If you aren't partial to using with, you can do

f = open("C:/out.txt","r+")
f.readlines()
f.write("This is a test\n")
f.close()

The f.readlines() will ensure that you write to the end of the file instead of overwriting the first line if you need to write more. As the other person said, you can also open with "a" too

Matthew
  • 672
  • 4
  • 11