Reputation: 879
I am appending lines to a file using open
mode:
Chimera=open("file.txt","a")
I do this in a loop.
I would like the file to be cleared if the script is re-run, instead of appending to a file created by a previous run. How can I do that?
here is an exemple
liste=["A","B","C"]
file= open("file.txt","a")
for i in liste:
print(i, file= file)
so I get the file.txt such as :
A
B
C
but if I run the same script again I get:
A
B
C
A
B
C
instead of just
A
B
C
Upvotes: 0
Views: 479
Reputation: 60947
Just open the file for writing and not appending. You can write multiple times to the same file object, "appending" content to the resulting file, even in write mode.
The difference is that write mode ("w"
) will start with an empty file each time, whereas append mode ("a"
) will append to whatever file already exists.
Basically, just do:
liste = ["A","B","C"]
with open("file.txt", "w") as liste_file:
for i in liste:
print(i, file=liste_file)
Upvotes: 1