How to rename a file in Python?

I am wondering about how I can use Python to rename a file (so that I can save JSON data safely). I suspect the os module is involved.

Repl link:

(Note the following was written by Phind, an AI)

To rename a file in Python, you can use the os.rename() function from the os module. The os.rename() function takes two arguments: the current name of the file or directory (source), and the new name (destination).

Here is a simple example of how you can rename a file from ‘a.txt’ to ‘b.kml’:

import os

os.rename('a.txt', 'b.kml')

If the file is not in the current working directory, you need to specify the full path of the file. Here is an example of how you can rename a file in a directory:

import os
old_file = os.path.join("directory", "a.txt")
new_file = os.path.join("directory", "b.kml")
os.rename(old_file, new_file)

If you want to rename multiple files, you can use a loop to iterate through the list of file names and execute the os.rename() function for each file. Here is an example of how you can rename multiple files:

import os

old_file_names = ["old_file1.txt", "old_file2.txt", "old_file3.txt"]
new_file_names = ["new_file1.txt", "new_file2.txt", "new_file3.txt"]

for i in range(len(old_file_names)):
    os.rename(old_file_names[i], new_file_names[i])

It is important to remember that if the file you are trying to rename does not exist, the os.rename() function will throw a FileNotFoundError. You can use a try-except block to handle this exception and print a message to the user:

import os

    os.rename(old_file_name, new_file_name)
except FileNotFoundError:
    print(f"{old_file_name} does not exist.")

When renaming files, it is critical to check whether the new file name already exists or not, as it will replace any existing file with the same name without any warning

If you want to rename the extension of a file, you can use the splitext() method of the os module to get the root/base of the filename, then add the new extension to it while renaming it using the rename() method


Thank you. I didn’t see your reply until after I had found the documentation for the os module at, though, so I already found what I was looking for. (Oops!)

My takeaway from this is that I should look at the Python Docs before posting on the forum.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.