Don't spend $10k on a bootcamp. Try our back-end career path first.
Back home

How to Check if a File Exists in Python

By Lane Wagner on Dec 8, 2021

When working with files in Python, you’ll often need to check if a file exists before you do anything else with it, such as reading from or writing to it. Luckily, the Python standard library makes this a piece of cake.

Use pathlib.Path.exists(path) to check for files and directories

from pathlib import Path

path_exists = Path.exists("home/dir/file.txt")

if path_exists:
    print("found it!")
else:
    print("not found :(")

Notice that path_exists will be True whether this is a file or a directory, it’s only checking if the path exists.

Note: On older versions of Python you may not have access to the pathlib module . If that’s the case, you can use os.path.exists().

from os.path import exists

path_exists = exists("home/dir/file.txt")

if path_exists:
    print("found it!")
else:
    print("not found :(")

A simple path to your career in back-end development

The pace of Boot.dev's JavaScript, Python and Go courses has been perfect for me. The diverse community in Discord is a blast, and other members are quick to help out with detailed answers and explanations.

- Daniel Gerep from Cassia, Brasil

Use pathlib.Path(path).is_file() to check for only files

from pathlib import Path

file_exists = Path.is_file("home/dir/file.txt")

if file_exists:
    print("found it!")
else:
    print("not found :(")

Use pathlib.Path(path).is_dir() to check for only directories

from pathlib import Path

dir_exists = Path.is_dir("home/dir")

if dir_exists:
    print("found it!")
else:
    print("not found :(")

Get a back-end job without spending $10k on a bootcamp

I was a field service engineer and I wanted to become a backend developer, but work and family limited my options. Since completing the back-end career path on Boot.dev, I now have a job offer in hand and I'm starting my career as a software developer!

- Özgür Yildirim from Germany

A symlink is a path that points to, or aliases another path in a filesystem.

from pathlib import Path

symlink_exists = Path.is_dir("home/dir/some_symlink")

if symlink_exists:
    print("found it!")
else:
    print("not found :(")

Learn back-end without spending $10,000+ on a bootcamp

Related Reading