Deleting Files in Python
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Deleting Files in Python

Kishore V

Deleting Files in Python

Python provides built-in support for removing files and directories using the os module. This allows your program to manage files safely and efficiently.

[Image representing the Python os module interacting with a computer file system, showing a file being deleted or sent to the trash bin]

Removing a File

To delete a file, first import the os module and then use the os.remove() function.

Example: Delete a File

# (Program runs silently if the file exists and is successfully deleted)

Check File Existence Before Deleting

To avoid errors (like a FileNotFoundError), it’s a highly recommended best practice to confirm that the file exists before attempting to remove it.

Example: Safe File Deletion

File deleted successfully.
  • Prevents runtime errors
  • Safer for real-world applications

Deleting a Folder

To remove an empty directory, use the os.rmdir() method. (Note: If the folder contains files, this method will fail. You would need the shutil.rmtree() method to delete non-empty folders).

Example: Remove an Empty Folder

# (Program runs silently if the empty folder is successfully deleted)
Our website uses cookies to enhance your experience. Learn More
Accept !