Skip to main content

How to rename a file or directory in Python

How to rename a file or directory in Python.

Here is a detailed step-by-step tutorial on how to rename a file or directory in Python:

Renaming a File or Directory in Python

To rename a file or directory in Python, you can make use of the os module, which provides functions to interact with the operating system. The os module contains a function called rename() that allows you to rename files and directories.

Here's how you can do it:

Step 1: Import the os module:

import os

Step 2: Specify the current path of the file or directory you want to rename. You can provide either an absolute path or a relative path:

current_path = 'path/to/current/file_or_directory'

Step 3: Specify the new name you want to give to the file or directory:

new_name = 'new_name'

Step 4: Use the os.rename() function to rename the file or directory:

os.rename(current_path, new_name)

That's it! The file or directory will be renamed with the new name you specified.

Examples

Let's look at a few examples to demonstrate how to rename files and directories using Python:

Example 1: Renaming a File

import os

current_path = 'path/to/current/file.txt'
new_name = 'new_file.txt'

os.rename(current_path, new_name)

In this example, we are renaming the file file.txt to new_file.txt.

Example 2: Renaming a Directory

import os

current_path = 'path/to/current/directory'
new_name = 'new_directory'

os.rename(current_path, new_name)

In this example, we are renaming the directory directory to new_directory.

Example 3: Renaming a File or Directory with a Different Path

import os

current_path = 'path/to/current/file_or_directory'
new_path = 'path/to/new/file_or_directory'

os.rename(current_path, new_path)

In this example, we are renaming the file or directory located at current_path to new_path.

Handling Exceptions

When using the os.rename() function, it's a good practice to handle any exceptions that may occur. For example, if the file or directory you are trying to rename does not exist or if you don't have the necessary permissions. You can use a try-except block to handle such exceptions:

import os

try:
os.rename(current_path, new_name)
except Exception as e:
print("An error occurred:", str(e))

By using exception handling, you can gracefully handle any errors that may occur during the renaming process.

That's it! You now know how to rename files and directories in Python using the os module.