Python – How to check for file exists (isfile), directory exists (isdir)

By | January 25, 2017

When coding in python, there is often a need to check for the presence of a particular directory, or for the existence of a particular file.

In this case, you should check using the API to check the existence of the directory or file.

In python, ‘isdir’ and ‘isfile’ APIs are provided in the os module to use the functionality.

Definition at docs.python.org (isfile, isdir)

Both isfile and isdir should be given the path to the file or directory you want to check as arguments, returning True if they exist, and False if they are not.

Examples of actual use are as follows.

 

Using os.path.isdir ()

1
2
3
4
5
6
>>> import os
>>> os.path.isdir("~/temp")
False
>>> os.path.isdir("/home/ubuntu/temp")
True
>>>

. You can not use ~/, which means home directory, as in the example above.
. If the actual directory exists, it will return True normally.

 

Using os.path.isfile ()

1
2
3
4
5
6
7
8
>>> import os
>>> os.path.isfile("/home/ubuntu/test_a.txt")
False
>>> os.path.isfile("/home/ubuntu/test.txt")
True
>>> os.path.isfile("test.txt")
True
>>>

. In the above example, the file /home/ubuntu/test.txt exists.
. Returns False if test_a.txt does not exist.
. If you check the existing test.txt, it returns True.
. If you do not use an absolute path and only want to write a file name, return the result of the file in the directory in which you are currently running python.

 

Using the wrong os.path.isdir ()

If an argument is given to a file name in isdir, what is the return value?

1
2
>>> os.path.isdir("/home/ubuntu/temp.txt")
False

If you use isdir for an existing file as above, False is returned.

You should use isdir and isfile to distinguish files and directories.

Leave a Reply

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