DEV Community

Srinivas Ramakrishna for ItsMyCode

Posted on • Originally published at itsmycode.com on

How to Rename a file in Python?

ItsMyCode |

The os module in Python comes in handy in performing any file operations. The rename() method is used to rename a file or directory in Python.

Python Rename File

Python rename() function can rename any file type or folder in Python.

Syntax

os.rename(src, dst)

Parameters

  • src: src is the source file name that needs to be renamed. If the function cannot find the file or is inaccessible, Python will raise an OSError.
  • dst: dst is the destination file name which is the new name of the file or directory

Note : If the dst already exists, then the FileExistsError will be thrown in Windows, and in the case of UNIX, an OSError will be thrown.

Example to rename a file in Python

# Import os module
import os

# file name old and new. This can be even absolute path
old_file_name = "python.txt"
new_file_name = "python_renamed.txt"

# use rename function to rename the file or directory
os.rename(old_file_name, new_file_name)

print("Successfully renamed a file !")
Enter fullscreen mode Exit fullscreen mode

Output

Successfully renamed a file !
Enter fullscreen mode Exit fullscreen mode

Python Rename Multiple Files

There are times where you may need to rename multiple files in the same directory recursive. Let’s say some automated batch job creates a new file with the same name, and you still need to back up the old files by just renaming them as old_filename then, you can use rename() method to perform batch rename.

Example to Rename Multiple Files in Python

The code is straightforward. We can use the os.listdir()method in a loop that can get all the files, iterates each file inside the loop, and use the rename() function to rename the file.

# Import os module
import os

# Batch rename all the file in the specified directory
for file in os.listdir("C:/Projects/Tryouts"):
    os.rename(file, f"C:/Projects/Tryouts/old_{file}")

Enter fullscreen mode Exit fullscreen mode

Output

old_test.txt
old_python.text
old_student.csv
Enter fullscreen mode Exit fullscreen mode

Note: You can give the src and dst in the absolute path or relative name depending on where the file is placed, and the code is running. In the example, we have used both absolute and relative file names.

The post How to Rename a file in Python? appeared first on ItsMyCode.

Top comments (1)

Collapse
 
cclauss profile image
Christian Clauss
from pathlib import Path

Path("python.txt").rename(Path("python_renamed.txt"))
Enter fullscreen mode Exit fullscreen mode