How to check if file is currently existing using os.path
<p>I am currently having a problem while checking if a file name entered by user already exists. This is the code that i am currently running, however when i run the code properly and go to save the data with a name that already exists. It prints the correct error caption "This file already exists" and returns them back to the menu of the program. I was wondering how i could have it. Is there a way so the program can ask the user to re-input the file name again?</p>

<pre><code>if Menuchoice =='4':
    if popJuveniles ==0:
        print("please take part in option 1 before running option 4")
    else:
        if csvdata ==1:
            print("please take part in option 3 before trying to save the file")
        else:
            import csv
            #file_name=input("What would you like to call your file?")
            filename1=input("what would you like to call your file?")
    if os.path.isfile(filename1):
        print("This file already exists")
        csvext='.csv'
        filename=filename1+csvext

        with open(filename,'a') as genfile:
                insects_writer = csv.writer(genfile)
                insects_writer.writerow(csvdata)
</code></pre>

<p>If you want a quick answer, I would use a <code>while</code> loop until the name is correct.</p>

<p>For example:</p>

<pre><code>while os.path.isfile(filename1):
    print("This file already exists")
    filename1=input("what would you like to call your file?")
</code></pre>

<p>Keep in mind though that you should not use <code>while</code> very frequently for various reasons.</p>

python