isFile() : This method returns true if file exists and is a regular file, note that if file doesn't exist then it returns false. isDirectory() : This method returns true if file is actually a directory, if path doesn't exist then it returns false.
The isDir() function is used to check a given file is a directory or not.
path. isdir() method in Python is used to check whether the specified path is an existing directory or not. This method follows a symbolic link, which means if the specified path is a symbolic link pointing to a directory then the method will return True.
os.path.isdir()
and os.path.isfile()
should give you what you want. See:
http://docs.python.org/library/os.path.html
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.
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.
import os
if os.path.isdir(d):
print "dir"
else:
print "file"
os.path.isdir('string')
os.path.isfile('string')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With