How to test a file or directory exists in Python?

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?

asked Feb 18, 2016 by anonymous

1 Answer

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.

answered Mar 15, 2016 by Eric Z Ma (44,280 points)
How to test a file or directory exists in C++? asked Dec 22, 2017 by anonymous

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...