How do you create a file name with an incrementing number in Python?
To create an incrementing file name in Python, run a while loop that checks the existence of a file, and if it exists, use Regex to modify the file name by replacing the integer at the end of the file with the next number. Continue looping until the file name does not exist in the destination folder.
Here’s an example Python script that demonstrates how this can easily be done:
As you can see from the above code the function I have created is labelled
and contains 5 parameters:
is the full file path explored,
is the starting index number to begin incrementing the file (if
is found to already exist),
is the string being prepended before the incrementing digit (default is
is the string being appended after the incrementing digit (default is an empty string) and
is the character defined to separate the file name from the extension (default is
Here is an example executing this function in a script. Assume the
folder contains the following files:
Assume further that the function above is placed into a file labelled
>>> import os
>>> import main
>>> main.file_name_increment(os.join(os.getcwd(), "temp", "test.txt"), 1)
As you can see from the REPL result the output is correct and generates the next available file name according to the path and increment.
Checking the existence of a file in a directory is common when you are creating files or scraping files from a website. However, to ensure you are not writing over existing files, it is prudent to check if the file already exists before writing or renaming. The above script is what I have used when downloading files from scraping websites where the downloaded file contains the same file name, i.e.
By using this script in your coding you will help to prevent naming clashes with your files.
Find out more about incrementing in Python here .