How to test a file or directory exists in Python?

Posted on In QA

In 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.

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *