Skip to Content

How To Create An Incrementing File Name In Python

How To Create An Incrementing File Name In Python

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 file_name_increment and contains 5 parameters: file_path is the full file path explored, start_idx is the starting index number to begin incrementing the file (if file_path is found to already exist), prepend_str is the string being prepended before the incrementing digit (default is "-"), append_str is the string being appended after the incrementing digit (default is an empty string) and sep 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 temp folder contains the following files:

  • test.txt
  • test-1.txt

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. image.png.

By using this script in your coding you will help to prevent naming clashes with your files.