In the os
module in Python, is there a way to find if a directory exists, something like:
>>> os.direxists(os.path.join(os.getcwd()), 'new_folder')) # in pseudocode
True/False
In the os
module in Python, is there a way to find if a directory exists, something like:
>>> os.direxists(os.path.join(os.getcwd()), 'new_folder')) # in pseudocode
True/False
You're looking for os.path.isdir
, or os.path.exists
if you don't care whether it's a file or a directory.
Example:
import os
print(os.path.isdir("/home/el"))
print(os.path.exists("/home/el/myfile.txt"))
So close! os.path.isdir
returns True
if you pass in the name of a directory that currently exists. If it doesn't exist or it's not a directory, then it returns False
.
Yes, use os.path.exists()
.
Python 3.4 introduced the pathlib
module into the standard library, which provides an object oriented approach to handle filesystem paths:
In [1]: from pathlib import Path
In [2]: p = Path('/usr')
In [3]: p.exists()
Out[3]: True
In [4]: p.is_dir()
Out[4]: True
In [5]: q = p / 'bin' / 'vim'
In [6]: q.exists()
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.
Yes use os.path.isdir(path)
We can check with 2 built in functions
os.path.isdir("directory")
It will give boolean true the specified directory is available.
os.path.exists("directoryorfile")
It will give boolead true if specified directory or file is available.
To check whether the path is directory;
os.path.isdir("directorypath")
will give boolean true if the path is directory
As in:
In [3]: os.path.exists('/d/temp')
Out[3]: True
Probably toss in a os.path.isdir(...)
to be sure.
Just to provide the os.stat
version (python 2):
import os, stat, errno
def CheckIsDir(directory):
try:
return stat.S_ISDIR(os.stat(directory).st_mode)
except OSError, e:
if e.errno == errno.ENOENT:
return False
raise
os provides you with a lot of these capabilities:
import os
os.path.isdir(dir_in) #True/False: check if this is a directory
os.listdir(dir_in) #gets you a list of all files and directories under dir_in
the listdir will throw an exception if the input path is invalid.
#You can also check it get help for you
if not os.path.isdir('mydir'):
print('new directry has been created')
os.system('mkdir mydir')