Python - Renaming and Deleting Files



Renaming and Deleting Files in Python

In Python, you can rename and delete files using built-in functions from the os module. These operations are important when managing files within a file system. In this tutorial, we will explore how to perform these actions step-by-step.

Renaming Files in Python

To rename a file in Python, you can use the os.rename() function. This function takes two arguments: the current filename and the new filename.

Syntax

Following is the basic syntax of the rename() function in Python −

os.rename(current_file_name, new_file_name)

Parameters

Following are the parameters accepted by this function −

  • current_file_name − It is the current name of the file you want to rename.

  • new_file_name − It is the new name you want to assign to the file.

Example

Following is an example to rename an existing file "oldfile.txt" to "newfile.txt" using the rename() function −

import os

# Current file name
current_name = "oldfile.txt"

# New file name
new_name = "newfile.txt"

# Rename the file
os.rename(current_name, new_name)

print(f"File '{current_name}' renamed to '{new_name}' successfully.")

Following is the output of the above code −

File 'oldfile.txt' renamed to 'newfile.txt' successfully.

Deleting Files in Python

You can delete a file in Python using the os.remove() function. This function deletes a file specified by its filename.

Syntax

Following is the basic syntax of the remove() function in Python −

os.remove(file_name)

Parameters

This function accepts the name of the file as a parameter which needs to be deleted.

Example

Following is an example to delete an existing file "file_to_delete.txt" using the remove() function −

import os

# File to be deleted
file_to_delete = "file_to_delete.txt"

# Delete the file
os.remove(file_to_delete)

print(f"File '{file_to_delete}' deleted successfully.")

After executing the above code, we get the following output −

File 'file_to_delete.txt' deleted successfully.
Advertisements