How to identify whether a file is normal file or directory

Viewed 26168

How do you check whether a file is a normal file or a directory using python?

7 Answers

As other answers have said, os.path.isdir() and os.path.isfile() are what you want. However, you need to keep in mind that these are not the only two cases. Use os.path.islink() for symlinks for instance. Furthermore, these all return False if the file does not exist, so you'll probably want to check with os.path.exists() as well.

import os

if os.path.isdir(d):
    print "dir"
else:
    print "file"

os.path.isdir('string')
os.path.isfile('string')

try this:

import os.path
if os.path.isdir("path/to/your/file"):
    print "it's a directory"
else:
    print "it's a file"

To check if a file/directory exists:

os.path.exists(<path>)

To check if a path is a directory:

os.path.isdir(<path>)

To check if a path is a file:

os.path.isfile(<path>)
Related