I'm writing to a file in three functions and i'm trying not overwrite the file. I want every time i run the code i generate a new filewith open("atx.csv", 'w')as output:writer = csv.writer(output)
I'm writing to a file in three functions and i'm trying not overwrite the file. I want every time i run the code i generate a new filewith open("atx.csv", 'w')as output:writer = csv.writer(output)
If you want to write to different files each time you execute the script, you need to change the file names, otherwise they will be overwritten.
import os
import csvfilename = "atx"i = 0
while os.path.exists(f"{filename}{i}.csv"):i += 1with open(f"{filename}{i}.csv", 'w') as output:writer = csv.writer(output)writer.writerow([1, 2, 3]) #or whatever you want to write in the file, this line is just an example
Here I use os.path.exists() to check if a file is already present on the disk, and increment the counter.
First time you run the script, you get axt0.csv, second time axt1.csv, and so on.
Replicate this for your three files.
EDIT
Also note that here I'm using formatted string literals which are available since python3.6. If you have an earlier version of python, use "{}{:d}.csv".format(filename, i)
instead of f"{filename}{i}.csv"
EDIT bis after comments
If the same file is needed to be manipulated by more functionsduring the execution of the script, the easiest thing came to my mind is to open the writer outside the functions and pass it as an argument.
filename = "atx"i = 0
while os.path.exists(f"{filename}{i}.csv"):i += 1with open(f"{filename}{i}.csv", 'w') as output:writer = csv.writer(output)foo(writer, ...) #put the arguments of your function instead of ...bar(writer, ...)etc(writer, ...)
This way each time you call one of the functions it writes to the same file, appending the output at the bottom of the file.
Of course there are other ways. You might check for the file name existence only in the first function you call, and in the others just open the file with the 'a'
options, to append the output.