Story – Python Delete File

Alex, the Python developer, had completed his project successfully and was about to submit it to his manager. He had tested the project thoroughly, and it worked without any errors. But before submitting it, he realized that he had some redundant files that he wanted to delete.

He opened his Python IDE and wrote a simple Python program to delete a file using the os module. The program was straightforward and easy to understand. Alex was confident that it would work without any issues.

import os

try:
    os.remove("file.txt")
    print("File deleted successfully")
except:
    print("Error while deleting file")

As soon as he ran the program, he got an error message: FileNotFoundError: [Errno 2] No such file or directory: 'file.txt'. Alex realized that the file he was trying to delete did not exist, and that was causing the error.

To handle this error, Alex added a check to see if the file exists before trying to delete it. If the file does not exist, the program will display a message that the file does not exist.

import os

file_name = "file.txt"

if os.path.exists(file_name):
    try:
        os.remove(file_name)
        print(f"{file_name} deleted successfully")
    except:
        print(f"Error while deleting {file_name}")
else:
    print(f"{file_name} does not exist")

Now when Alex ran the program, it worked perfectly fine. The program first checked if the file exists and then tried to delete it. If the file did not exist, the program displayed a message saying that the file did not exist.

Alex was happy that he had fixed the issue and could now submit his project to his manager.