首页 文章

如何查找Python中是否存在目录

提问于
浏览
832

在Python的 os 模块中,有没有办法找到目录是否存在,例如:

>>> os.direxists(os.path.join(os.getcwd()), 'new_folder')) # in pseudocode
True/False

10 回答

  • 6

    我们可以查看2个内置功能

    os.path.isdir("directory")
    

    如果指定的目录可用,它将给出布尔值true .

    os.path.exists("directoryorfile")
    

    如果指定的目录或文件可用,它将使boolead为true .

    检查路径是否是目录;

    os.path.isdir("directorypath")

    如果路径是目录,则将布尔值设为true

  • 58

    如:

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

    可能会折腾 os.path.isdir(...) .

  • 31
    #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')
    
  • 1293

    是的,请使用os.path.exists() .

  • 4

    只是提供 os.stat 版本(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
    
  • 5

    你正在寻找os.path.isdir,或者os.path.exists,如果你没有't care whether it'是一个文件或目录 .

    例:

    import os
    print(os.path.isdir("/home/el"))
    print(os.path.exists("/home/el/myfile.txt"))
    
  • 14

    很近!如果传入当前存在的目录的名称, os.path.isdir 将返回 True . 如果它不是't exist or it'不是目录,则它返回 False .

  • 9

    os为您提供了许多这些功能:

    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
    

    如果输入路径无效,listdir将抛出异常 .

  • 11

    Python 3.4将the pathlib module引入标准库,它提供了一种面向对象的方法来处理文件系统路径:

    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也可以在Python 2.7上通过the pathlib2 module on PyPi.获得

  • 22

相关问题