Renaming and Deleting Files in Python

In Python, you can easily rename and delete files using the os module. This module provides a portable way of using operating system-dependent functionality, including file operations.

Renaming Files

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

Example of Renaming a File

# Renaming a file
        import os
        
        # Original file name
        original_file = "old_file.txt"
        # New file name
        new_file = "new_file.txt"
        
        # Renaming the file
        os.rename(original_file, new_file)
        print("File renamed from", original_file, "to", new_file)

Output

File renamed from old_file.txt to new_file.txt

Deleting Files

To delete a file, you can use the os.remove() function. This function takes one argument: the file name you want to delete.

Example of Deleting a File

# Deleting a file
        import os
        
        # File name to delete
        file_to_delete = "new_file.txt"
        
        # Deleting the file
        os.remove(file_to_delete)
        print("File", file_to_delete, "has been deleted.")

Output

File new_file.txt has been deleted.

Handling Exceptions

It is a good practice to handle exceptions when renaming or deleting files, as the file may not exist or you may not have the necessary permissions.

Example with Exception Handling

# Renaming and deleting a file with exception handling
        import os
        
        try:
            # Renaming a file
            os.rename("non_existent_file.txt", "renamed_file.txt")
        except FileNotFoundError:
            print("Error: The file does not exist.")
        
        try:
            # Deleting a file
            os.remove("non_existent_file.txt")
        except FileNotFoundError:
            print("Error: The file does not exist.")

Output

Error: The file does not exist.
Error: The file does not exist.

Conclusion

Renaming and deleting files in Python is straightforward with the os module. Always remember to handle exceptions to ensure your program can gracefully handle scenarios where files may not exist.