Python check file exists

Python has built-in module os for interacting with operating system. It has function exists to check if file exists. It returns True if file exists and False otherwise.

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

We will use documents directory in this notebook:

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

# import packages
from os.path import exists

Checking file which does exist.

# check if file exists and assign this information to variable
my_file_exists = exists(r"/home/piotr/documents/my-cv.pdf")
# display information
if my_file_exists:
    print(f"File /home/piotr/documents/my-cv.pdf exists")
else:
    print(f"File /home/piotr/documents/my-cv.pdf does not exists")

Checking files which doesn't exist.

# check if file exists and assign this information to variable
my_file_exists = exists(r"/home/piotr/documents/music/no-such-file.mp3")
# display information
if my_file_exists:
    print(f"File /home/piotr/documents/music/no-such-file.mp3 exists")
else:
    print(f"File /home/piotr/documents/music/no-such-file.mp3 does not exists")

In the above code nisppets, we have used if condition to display message about file. You can put your custom code in the if condition.

Recipes used in the python-check-file-exists.ipynb

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

Packages used in the python-check-file-exists.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.