How to test a file or directory exists in Python?
Posted on In QAIn Bash, the [ -f ]
and [ -d ]
tests can test whether a file or a directory exist. What are the corresponding python method for these tests?
For -f
:
**os.path.isfile(path)**
Return True if path is an existing regular file. This follows symbolic links.
For -d
:
**os.path.isdir(path)**
Return True if path is an existing directory. This follows symbolic links.
As they follow symbolic links (in Bash, -d
and -f
do too), if you are interested filter symbolic links out, you can use
**os.path.islink(path)**
Return True if path refers to a directory entry that is a symbolic link. Always False if symbolic links are not supported by the python runtime.