Python (Scripting) - Determine if a file or directory exists

by
Jeremy Canfield |
Updated: April 01 2024
| Python (Scripting) articles
os.path.exists can be used to determine if a file or directory exists and os.mkdir can be used to create the directory if it does not exist.
#!/usr/bin/python
import os.path
if os.path.exists("/usr/local/foo"):
print("/usr/local/foo exists")
else:
print("/usr/local/foo does not exist")
os.mkdir("/usr/local/foo")
Or like this, using False.
#!/usr/bin/python
import os.path
if os.path.exists("/usr/local/foo") == False:
print("/usr/local/foo does not exist")
os.mkdir("/usr/local/foo")
else:
print("/usr/local/foo exists")
Or like this, using not.
#!/usr/bin/python
import os.path
if not os.path.exists("/usr/local/foo"):
print("/usr/local/foo does not exist")
os.mkdir("/usr/local/foo")
else:
print("/usr/local/foo exists")
Or, sometimes you may want to go with os.path.abspath.
#!/usr/bin/python3
import os.path
foo = "/usr/local/foo"
if os.path.abspath(foo):
print(f"{foo} exists")
else:
print(f"{foo} does NOT exist")
os.mkdir("/usr/local/foo")
Better yet, using a variable.
#!/usr/bin/python3
import os.path
foo = "/usr/local/foo"
if os.path.exists(foo):
print(f"{foo} exists")
else:
print(f"{foo} does NOT exist")
Or, for best performance, scandir can be used.
#!/usr/bin/python
import os
for entry in os.scandir('/usr/local/foo'):
if not entry.name.startswith('.') and entry.is_dir():
print(entry.name)
Did you find this article helpful?
If so, consider buying me a coffee over at