DEV Community

loading...

How to Check a File or Directory Exists in Python

serhatteker profile image Serhat Teker Originally published at tech.serhatteker.com on ・2 min read

If it doesn't matter it is a file or directory you can use os.path.exists():

# check_exists.py
import os

file = "/home/user/tmp/file"
dir = "/home/user/tmp/dir"

if __name__ == "__main__":
    print("File exists: ", os.path.exists(file))
    print("Dir exists: ", os.path.exists(dir))
Enter fullscreen mode Exit fullscreen mode

NOTE:

I'm using if __name__ == "__main__" notation. If you want to see more
information about this look this article: What does if name __name__ == "__main__" do in Python

When you run the file you will see similiar output like below:

$ python check_exists.py

File exists: True
Dir exists: True
Enter fullscreen mode Exit fullscreen mode

You may be a little bit confused, since In Unix-like systems — MacOs and Linux,script files don't have to need file extensions like file.sh or file.py. All you need is a shebang#!. For instance this is the content of /home/user/tmp/file:

# /home/user/tmp/file
#!/bin/bash

# make a tmp/ dir at $HOME if not exists with verbose input
mkdir -pv ~/tmp
Enter fullscreen mode Exit fullscreen mode

NOTE:

Using ~/ alias like ~/tmp/dir doesn't work. You need to give absolute
path or expand the alias: os.path.expanduser('~/tmp/file')

File

If you want to check a file exists and got file type:

# check_file_exists.py
import os

file = "/home/user/tmp/file"

if __name__ == "__main__":
    print("File exists AND a file: ", os.path.isfile(file))
Enter fullscreen mode Exit fullscreen mode

Directory

You can check directory with os.path.isdir function:

# check_dir_exists.py
import os

dir = "/home/user/tmp/dir"

if __name__ == "__main__":
    print("Dir exists AND a directory: ", os.path.isdir(dir))
Enter fullscreen mode Exit fullscreen mode

Bonus:Create If Not Exists

Also if you want to create one if this doesn't exist:

# check_exists_or_create.py
import os

file = "/home/user/tmp/file"
dir = "/home/user/tmp/dir"

if __name__ == "__main__":
    # create dir if not exists
    if not os.path.isdir(dir):
        os.mkdir(dir)

    # create file if not exists
    if not os.path.isfile(file):
        open(file, 'w').close()

    # alternative to create file if not exists
    from pathlib import Path
    Path(file).touch()
Enter fullscreen mode Exit fullscreen mode

All done!

Discussion (2)

pic
Editor guide
Collapse
alibas13 profile image
Ali Bas

Very nice explain.
What about a file or directory located in network LAN?

Collapse
kamarajanis profile image
Kamaraj

Very Informative , thank you