How to Delete Files in Python: A Complete Guide

Master the process of deleting files in Python with our comprehensive guide. Learn how to use the os.remove() function to delete files, check if a file exists before deletion, and remove entire folders. Get practical tips and examples to handle file management tasks efficiently.



Python Delete File

Deleting files is a common task in Python. This guide covers how to delete a file, check if a file exists before deleting it, and remove an entire folder.

Delete a File

To delete a file, you must import the OS module and use its os.remove() function:

Example

import os
os.remove("demofile.txt")

Check if File Exists Before Deleting

To avoid getting an error, check if the file exists before you try to delete it:

Example

import os
if os.path.exists("demofile.txt"):
    os.remove("demofile.txt")
else:
    print("The file does not exist")

Delete a Folder

To delete an entire folder, use the os.rmdir() method:

Example

import os
os.rmdir("myfolder")

Note: You can only remove empty folders.