Search code examples
pythonoperating-systembuilt-infile-manager

How to create a file with '01' if name exists?


Is there a specific argument in open() built-in function so that if the filename already exists, it creates a file by adding a number to its name ??

such that if "file.txt" exists, it automatically creates "file-01.txt"

Or any other solution.!


Solution

  • I have found a solution, Thanks!!

    b = True
    c = 1
    while b:
        f_name = 'Task-{:02.0f}.txt'.format(c)
        try:
            f = open(f_name,'x')
            b = False
        except FileExistsError:
            c += 1
    f.close()