How to delete a file using Python code example

There are two modules os and pathlib you can make use of to delete a file using Python code, let us see some examples,

Example 1: Using the os module
import os

file = "/Users/code2care/PycharmProjects/pythonProject/sample.txt"

if os.path.exists(file):
    print("File: " + file + " deleted ...")
    print("File not found: " + file + " ...")

Example 2: Using the pathlib module
import pathlib

fileStr = "/Users/code2care/PycharmProjects/pythonProject/sample.txt"
file = pathlib.Path(fileStr)

if file.exists():
    print("File: " + fileStr + " deleted ...")
    print("File not found: " + fileStr + " ...")
Output - Delete file using Python code
Output - Delete file using Python code

Note if you do not handle the code to look if the file exists or not you will get a FileNotFoundError,

Traceback (most recent call last):
  File "/Users/c2c/PycharmProjects/pythonProject/", line 5, in 
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/", line 1344, in unlink
FileNotFoundError: [Errno 2] No such file or directory: '/Users/c2c/PycharmProjects/pythonProject/sample.txt'
Try Out Code2care Dev Tools:


Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.