I have a program that outputs a file and asks the user to provide a file name. My issue concerns what happens when the user provides a file name that already exists. For example, suppose the user wants their data to be written to foo.txt
but it already exists. I want to output their data instead to foo (1).txt
. Is there a Python module that does this for you or is there a better way to do it than what I'm currently doing?
The way I am currently doing this is as shown.
def determine_file_name(name):
counter = 0
file_name = '{0}.tex'.format(name)
while os.path.exists(file_name):
counter += 1
file_name = '{0} ({1}).tex'.format(name, counter)
return file_name