How to find if directory exists in Python

2019-01-09 21:22发布

问题:

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

回答1:

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"))


回答2:

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.



回答3:

Yes, use os.path.exists().



回答4:

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.



回答5:

Yes use os.path.isdir(path)



回答6:

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



回答7:

As in:

In [3]: os.path.exists('/d/temp')
Out[3]: True

Probably toss in a os.path.isdir(...) to be sure.



回答8:

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


回答9:

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.



回答10:

#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')