162

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

dreftymac
  • 31,404
  • 26
  • 119
  • 182

7 Answers7

183

os.path.isdir() and os.path.isfile() should give you what you want. See: http://docs.python.org/library/os.path.html

PTBNL
  • 6,042
  • 4
  • 28
  • 34
43

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.

retracile
  • 12,167
  • 4
  • 35
  • 42
27

Python 3.4 introduced the pathlib module into the standard library, which provides an object oriented approach to handle filesystem paths. The relavant methods would be .is_file() and .is_dir():

In [1]: from pathlib import Path

In [2]: p = Path('/usr')

In [3]: p.is_file()
Out[3]: False

In [4]: p.is_dir()
Out[4]: True

In [5]: q = p / 'bin' / 'vim'

In [6]: q.is_file()
Out[6]: True

In [7]: q.is_dir()
Out[7]: False

Pathlib is also available on Python 2.7 via the pathlib2 module on PyPi.

joelostblom
  • 43,590
  • 17
  • 150
  • 159
8
import os

if os.path.isdir(d):
    print "dir"
else:
    print "file"
Dominic Rodger
  • 97,747
  • 36
  • 197
  • 212
3

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>)
Sheva Kadu
  • 91
  • 9
3

os.path.isdir('string')
os.path.isfile('string')
erenon
  • 18,838
  • 2
  • 61
  • 93
3

try this:

import os.path
if os.path.isdir("path/to/your/file"):
    print "it's a directory"
else:
    print "it's a file"
uolot
  • 1,480
  • 1
  • 13
  • 18