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):
    os.remove(file)
    print("File: " + file + " deleted ...")
else:
    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():
    file.unlink()
    print("File: " + fileStr + " deleted ...")
else:
    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,

Error:
Traceback (most recent call last):
  File "/Users/c2c/PycharmProjects/pythonProject/main.py", line 5, in <module>
    file.unlink()
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/pathlib.py", line 1344, in unlink
    self._accessor.unlink(self)
FileNotFoundError: [Errno 2] No such file or directory: '/Users/c2c/PycharmProjects/pythonProject/sample.txt'

References:

  1. https://docs.python.org/3/library/os.html
  2. https://docs.python.org/3/library/pathlib.html
  3. https://docs.python.org/3/library/exceptions.html
  4. https://docs.python.org/3/library/os.path.html?highlight=path#module-os.path
  5. https://docs.python.org/3/library/os.html?highlight=unlink#os.unlink

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap