Python (Scripting) - Determine if an object is a file or directory (os.path.isfile isdir)

by
Jeremy Canfield |
Updated: April 01 2024
| Python (Scripting) articles
In a Python script, the os.path module can be used to determine if a path is a file or a directory. You will typically want to also first use os.path.exists to determine if the path exists.
#!/usr/bin/python
import os.path
if os.path.exists("/usr/local/foo"):
print "/usr/local/foo exists"
if os.path.isfile("/usr/local/foo"):
print "/usr/local/foo is a file"
elif os.path.isdir("/usr/local/foo"):
print "/usr/local/foo is a directory"
else:
print "/usr/local/foo does not exist"
Better yet, using a variable.
#!/usr/bin/python3
import os.path
foo = "/usr/local/foo"
if os.path.exists(foo):
print(f"{foo} exists")
if os.path.isfile(foo):
print(f"{foo} is a file")
elif os.path.isdir(foo):
print(f"{foo} is a directory")
else:
print(f"{foo} does NOT exist")
Did you find this article helpful?
If so, consider buying me a coffee over at