0

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
grenmester
  • 95
  • 10
  • I don't think there is an out of the box way to do this. The way you are doing this is similar to what [this](https://stackoverflow.com/q/17984809/5028532) questions shows. I don't think there is anything wrong with it. – razdi May 24 '19 at 00:43
  • For Certain use cases Timestamps will help you out too. But there aren't many of them – Vasu Deo.S May 24 '19 at 00:49
  • 1
    This is also how OS's actually implement that. Keep using your code it's good!!! – babaliaris May 24 '19 at 01:54

0 Answers0