Skip to content Skip to sidebar Skip to footer

Creating File Loop

How can I ask the user for a file name and if it already exists, ask the user if they want to overwrite it or not, and obey their request. If the file does not exist, a new file (w

Solution 1:

Alternative soltution would be (however the user would need to provide a full path):

import os

def func():
    ifos.path.exists(input("Enter name: ")):
        ifinput("File already exists. Overwrite it? (y/n) ")[0] == 'y':
            my_file = open("filename.txt", 'w+')
        else:
            func()

    else:
    my_file = open("filename.txt", 'w+')

Don't forget to close the file object when it's not needed anymore with my_file.close().

Solution 2:

You can use os.path.exists to check if a file already exists are not.

ifos.path.exists(file path):
    q = input("Do you want to overwrite the existing file? ")
    if q == (your accepted answer):
       #stuff
else:
    #stuff

You could do this with a try / except if you want to abide by the whole "easier to ask for forgiveness" motto, but I think this is cleaner.

Post a Comment for "Creating File Loop"