Python delete file

You can use Python to automate file delete in your file system. You can use os Python built-in module and remove() function. It is a good practice to check if file exists before delete.

This notebook was created with MLJAR Studio

MLJAR Studio is Python code editior with interactive code recipes and local AI assistant.
You have code recipes UI displayed at the top of code cells.

Documentation

The documents directory before running os.remove():

documents/
├── music
│   ├── bass-guitar-sample.mp3
│   ├── first-song.mp3
│   ├── italo-disco.mp3
│   └── rave.wav
├── my-cv.pdf
├── phd-thesis.txt
├── todo.txt
└── video
    ├── holidays-2023.mp4
    ├── holidays-2024.mp4
    └── zoo.mov

2 directories, 10 files
# import packages
import os
# check if file path exists
if os.path.isfile(r"/home/piotr/documents/todo.txt"):
    # file exists, delete it
    os.remove(r"/home/piotr/documents/todo.txt")
else:
    print("File not found")

The documents after running os.remove():

documents/
├── music
│   ├── bass-guitar-sample.mp3
│   ├── first-song.mp3
│   ├── italo-disco.mp3
│   └── rave.wav
├── my-cv.pdf
├── phd-thesis.txt
└── video
    ├── holidays-2023.mp4
    ├── holidays-2024.mp4
    └── zoo.mov

2 directories, 9 files

As you can see there is no todo.txt file any more in documents directory, so I'm free person 😊

It is important to remember that you can pass full path to the file or just file name. In the case of passing just file name, the file will be removed in the current directory - the directory where you start Python.

Recipes used in the python-delete-file.ipynb

All code recipes used in this notebook are listed below. You can click them to check their documentation.

Packages used in the python-delete-file.ipynb

List of packages that need to be installed in your Python environment to run this notebook. Please note that MLJAR Studio automatically installs and imports required modules for you.