0

I am a Python beginner. I made a script which, after doing what it is supposed to do, creates a file called "report.csv" with some datas I need.

This is how that part of code looks like:

with open('report.csv'), 'x', newline='') as report_file:
    report_writer = csv.writer(report_file)
    report_writer.writerows(array_i_have_to_write_in_csv)

If report.csv does not exists, everything works perfectly. Otherwise, it throws FileExistsError exception.

I'd like to handle it naming files with a progressive number, like "report-001.csv", "report-002.csv", etc. but how can I do that?

Thanks

Dario Costa
  • 33
  • 1
  • 8

1 Answers1

1

you can use f-strings (https://docs.python.org/3/tutorial/inputoutput.html) to name your file:

with open(f"report{i}.csv", "x") as report_file:
    #do sth

now you have to check if report{i}.csv exists in your current working directory.

def incrementForFilename():
    # get current working directory
    cwd = Path.cwd()
    i = 0
    # loop until you find an i, that does not exist in cwd
    while Path(cwd, f"report{i}.csv").is_file():
        i +=1
    return i

you have to run this function before creating your file:

i = incrementForFilename()
with open(f"report{i}.csv", "x") as f:
    f.writelines("something")

Hope this helps.

Franklynn
  • 28
  • 4