How to Check a File or Directory Exists in Python
If it doesn’t matter it is a file or directory you can use os.path.exists()
:
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))
Info
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
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
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:
import os
file = "/home/user/tmp/file"
if __name__ == "__main__":
print("File exists AND a file: ", os.path.isfile(file))
Directory
You can check directory with os.path.isdir
function:
import os
dir = "/home/user/tmp/dir"
if __name__ == "__main__":
print("Dir exists AND a directory: ", os.path.isdir(dir))
Bonus:Create If Not Exists
Also if you want to create one if this doesn’t exist:
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()
All done!