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 + " ...")

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
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:
- https://docs.python.org/3/library/os.html
- https://docs.python.org/3/library/pathlib.html
- https://docs.python.org/3/library/exceptions.html
- https://docs.python.org/3/library/os.path.html?highlight=path#module-os.path
- https://docs.python.org/3/library/os.html?highlight=unlink#os.unlink
Have Questions? Post them here!
- tkinter - Hello World! Program
- How to install Python Specific version (3.8, 3.9 or 3.10) using Brew
- How to install SpaCy (NLP Library) on Mac
- Python matplotlib segmentation fault: 11 macOS Big Sur
- How to uninstall pip Python packages
- 3 Ways to find if element is present in a List in Python
- How to Convert Python String to DateTime Object
- Python f-strings Formatted String Literals Syntax and Examples
- Where does brew install python in macOS
- Take input argument from command line in Python Programming
- Advanced print() Function Tutorial and Techniques for Python Developers
- How to add borders to tkinter label text
- Whats new in Python 3.10 Pre-release
- Float built-in function in Python
- List of All 35 Reserved Keywords in Python Programming Language 3.11
- How to check if Key Exists in Python Dictionary?
- Read a file line by line in Python Program
- ModuleNotFoundError: No module named qdarkstyle.colorsystem [Python]
- What is the Max and Minimum Value of int type in Python?
- What is Terminal Velocity and its Formula? How to calculate it programmatically?
- Fix: TypeError: can only concatenate str (not int) to str in Python
- How to take user input from the console in a Python program
- [Fix] TypeError: str object is not callable in Python
- 3 Python program to add two numbers
- How to delete a file using Python code example
- Create Hidden File or Directory using Shell Command - Linux
- MacoOS - xyz is an app downloaded from the internet. Are you sure you want to open it? Alert - MacOS
- How To Change Mac Terminal Text Color - MacOS
- How to add two float numbers in Python - Python
- Java Get Current Date for a Specific Time Zone - Java
- How to run Gradle build in offline mode - Gradle
- [Gmail] Calling in Hangouts will be turned off soon. - News
- Run Scripting Language (JavaScript, Python, Groovy, Ruby) in Java - Java