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
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'
More Posts related to Python,
- Comments in Python Programming
- tkinter - Hello World! Program
- How to install Python 3.11 on Mac
- Python matplotlib segmentation fault: 11 macOS Big Sur
- Change label (text) color in tkinter
- Python Hello World! Program with code example (snippet)
- Calculate discount amount python code
- Take input argument from command line in Python Programming
- How to pip install Python Modules in VSCode
- Tkinter - add x and y padding to label text
- Python raise error with message example
- Check if String Contains a Substring - Python
- Python Program To Calculate Simple Interest (SimpleInterest.py)
- What does b prefix before a String mean in Python?
- What is Terminal Velocity and its Formula? How to calculate it programmatically?
- How to List all Packages installed using pip [Python]
- Convert Float to String in Python
- Change the background of Tkinter label or text
- How to Install Python Modules in VS Code
- Indent Python code in Notepad++
- Validate email address in Python using regular expression (regex)
- Python: Fix command not found pip or pip3 on zsh shell
- TypeError: must be str, not int [Fix Python]
- ModuleNotFoundError: No module named qdarkstyle.colorsystem [Python]
- Python - Convert float to String
More Posts:
- [Fix] Microsoft 53003 Error - Microsoft
- Setting $JAVA_HOME Environment Variable in macOS - MacOS
- How to add hint text in bootstrap input text field and text area - Bootstrap
- Unzip a Zip file from Terminal Command - HowTos
- 12 August - International Youth Day celebrated worldwide - News
- Enable Dark Mode in Google Search - Google
- Build-in Snipping Tool Alternative on Mac - MacOS
- 21 Useful Android Emulator Short-cut Keyboard Keys - Android