Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

Python File Management: Rename & Delete Files with Ease

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 −

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.

Python

  1. Master Running Python Scripts: A Comprehensive Step‑by‑Step Guide
  2. Python Modules: Organizing Your Code for Clarity and Reusability
  3. Efficiently Measure Python Object Memory Usage with sys.getsizeof()
  4. Mastering Inter-Thread Communication in Python: Synchronization & Data Sharing
  5. Master Python String Operations: Replace, Join, Split, Reverse, and Case Conversion
  6. Master Python Conditional Statements: IF, ELSE, ELIF, and Switch‑Like Logic
  7. The Zen of Python: 19 Timeless Principles for Elegant Coding (PEP-20)
  8. Master Python Debugging: Efficient Techniques & Best Practices
  9. Mastering Python I/O and Module Imports: A Practical Guide
  10. Python Lambda Functions: A Practical Guide to Anonymous Functions