How to Increment a Filename in Python?

Challenge: Given a Python program that writes data into a file. If you run the program again, it’ll overwrite the file written by the first execution of the program.

file = open("file.dat", "w")

# ... Do some processing ...

file.write("Result of program")
file.close()

Each time you run this program, the original content in file.dat will be overwritten.

How to avoid this overwriting by adding an integer suffix to the filename and incrementing it by one each time you rerun the program?

What You Want:
--- file_1.dat                        # Execution 1
--- file_2.dat                        # Execution 2
...
--- file_n.dat                        # Execution n

Solution: os.path.exist()

Create a count variable i and increment it by one in a while loop as long as file_i.dat exists—using the os.path.exist() method to check the existence. After leaving the loop, the variable i is set to the first unused integer in a filename. Now, open file_i.dat, write the content, and close it. No file will be overwritten.

Here’s the full program:

import os

# Determine incremented filename
i = 0
while os.path.exists(f"file_{i}.dat"):
    i += 1

file = open(f"file_{i}.dat", "w")

# ... Do some processing ...

file.write("Result of program")
file.close()

The program performs the following steps:

  • Determine the identifier i by going over all integers, increment them by one in each loop iteration, until you find the first integer that doesn’t yet exist in a filename.
  • Use the os.path.exist() method to check whether the filename exists.
  • Use a format string f"file_{i}.dat" to create the names file_1.dat, file_2.dat, …

After running this program three times, you obtain the following three files in the same folder your program resides:

What You Get:
--- file_1.dat                        # Execution 1
--- file_2.dat                        # Execution 2
--- file_3.dat                        # Execution 3

Resources: