【问题标题】:How to find if directory exists in Python如何在Python中查找目录是否存在
【发布时间】:2012-02-14 12:51:57
【问题描述】:

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

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

【问题讨论】:

  • 一句警告 - 评分最高的答案可能容易受到竞争条件的影响。您可能希望改为执行os.stat,以查看该目录是否同时存在并且是一个目录。
  • @d33tah 您可能有一个好点,但我看不到使用os.stat 来区分文件目录的方法。当路径无效时,无论是文件还是目录,它都会引发OSError。此外,检查后的任何代码也容易受到竞争条件的影响。
  • @TomášZato:得出的结论是只执行操作和处理错误是安全的。
  • @David542 我添加了一个澄清案例,其中包含“isdir”“存在”的精度测试。我想你现在会学到任何东西。但它可以照亮新人。
  • 也许this answer 有助于os.stat 的使用

标签: python directory


【解决方案1】:

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

【讨论】:

  • 那不检查路径是否为目录。
  • 好电话。其他人指出os.path.isdir 将实现这一目标。
  • 如果你明白这不能回答问题,为什么不删除答案?
  • @CamilStaps 这个问题被浏览了 354000 次(到目前为止)。这里的答案不仅适用于 OP,而且适用于任何可能出于任何原因来到这里的人。 aganders3 的回答是中肯的,即使它不能直接解决 OP 的问题。
  • @Gabriel 那么应该在答案中明确说明这实际上是做什么的。
【解决方案2】:

你正在寻找os.path.isdir,或者os.path.exists,如果你不在乎它是一个文件还是一个目录:

>>> import os
>>> os.path.isdir('new_folder')
True
>>> os.path.exists(os.path.join(os.getcwd(), 'new_folder', 'file.txt'))
False

或者,您可以使用pathlib

 >>> from pathlib import Path
 >>> Path('new_folder').is_dir()
 True
 >>> (Path.cwd() / 'new_folder' / 'file.txt').exists()
 False

【讨论】:

  • @syedrakib 虽然括号可以用来表示一个对象是可调用的,但这在 Python 中没有用,因为即使是类也是可调用的。此外,函数是 Python 中的一等值,您可以不使用括号符号来使用它们,例如existing = filter(os.path.isdir(['/lib', '/usr/lib', '/usr/local/lib'])
  • 您可以将函数传递给其他函数,例如map,但在一般情况下,您调用带有参数和括号的函数。此外,您的示例中有一些错字。大概你的意思是filter(os.path.isdir, ['/lib', '/usr/lib', '/usr/local/lib'])
  • 还有os.path.isfile(path)如果你只关心它是不是一个文件。
  • 请注意,在某些平台上,如果文件/目录存在,这些将返回 false,但也会发生读取权限错误。
  • 上面的例子是不可移植的,如果使用 os.path.join 或者下面推荐的 pathlib 东西重写会更好。像这样的东西: print(os.path.isdir(os.path.join('home', 'el')))
【解决方案3】:

如:

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

可以肯定的是os.path.isdir(...)

【讨论】:

    【解决方案4】:

    如此接近!如果您传入当前存在的目录的名称,os.path.isdir 将返回 True。如果不存在或者不是目录,则返回False

    【讨论】:

      【解决方案5】:

      是的,使用os.path.isdir(path)

      【讨论】:

        【解决方案6】:

        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 会抛出异常。

        【讨论】:

          【解决方案7】:

          只提供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
          

          【讨论】:

          • 使用staterrno 代替pathlib2 有什么好处?是d33tah对该问题的评论中提到的竞争条件吗?
          【解决方案8】:

          Python 3.4 将the pathlib module 引入标准库,它提供了一种面向对象的方法来处理文件系统路径。 Path 对象的 is_dir()exists() 方法可以用来回答这个问题:

          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
          Out[6]: PosixPath('/usr/bin/vim') 
          
          In [7]: q.exists()
          Out[7]: True
          
          In [8]: q.is_dir()
          Out[8]: False
          

          Pathlib 也可通过the pathlib2 module on PyPi. 在 Python 2.7 上使用

          【讨论】:

          • 一些解释会有所帮助。你为什么要做“p / 'bin' / 'vim'
          • @frank 我详细阐述了答案的第二部分。
          【解决方案9】:
          #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')
          

          【讨论】:

          • python有内置函数来创建目录,所以最好使用os.makedirs('mydir')而不是os.system(...)
          • 您正在打印 '新目录已创建',但您不知道。如果您没有创建目录的权限怎么办?你会打印 'new directory has been created' 但这不是真的。会吗。
          【解决方案10】:

          我们可以检查两个内置函数

          os.path.isdir("directory")
          

          它将给出布尔值 true 指定的目录可用。

          os.path.exists("directoryorfile")
          

          如果指定的目录或文件可用,它将给 boolead true。

          检查路径是否为目录;

          os.path.isdir("directorypath")

          如果路径是目录,将给出布尔值 true

          【讨论】:

          • 这与旧的顶级答案完全是多余的。
          【解决方案11】:

          有一个方便的Unipath 模块。

          >>> from unipath import Path 
          >>>  
          >>> Path('/var/log').exists()
          True
          >>> Path('/var/log').isdir()
          True
          

          您可能需要的其他相关内容:

          >>> Path('/var/log/system.log').parent
          Path('/var/log')
          >>> Path('/var/log/system.log').ancestor(2)
          Path('/var')
          >>> Path('/var/log/system.log').listdir()
          [Path('/var/foo'), Path('/var/bar')]
          >>> (Path('/var/log') + '/system.log').isfile()
          True
          

          你可以使用 pip 安装它:

          $ pip3 install unipath
          

          类似于内置的pathlib。不同之处在于它将每条路径都视为字符串(Pathstr 的子类),因此如果某个函数需要字符串,您可以轻松地将Path 对象传递给它,而无需将其转换为一个字符串。

          例如,这适用于 Django 和 settings.py

          # settings.py
          BASE_DIR = Path(__file__).ancestor(2)
          STATIC_ROOT = BASE_DIR + '/tmp/static'
          

          【讨论】:

            【解决方案12】:

            如果目录不存在,您可能还需要创建目录。

            Source,如果它还在 SO 上。

            ================================================ =======================

            在 Python ≥ 3.5 上,使用pathlib.Path.mkdir

            from pathlib import Path
            Path("/my/directory").mkdir(parents=True, exist_ok=True)
            

            对于旧版本的 Python,我看到两个质量很好的答案,每个都有一个小缺陷,所以我会给出我的看法:

            尝试os.path.exists,并考虑使用os.makedirs 进行创建。

            import os
            if not os.path.exists(directory):
                os.makedirs(directory)
            

            如 cmets 和其他地方所述,存在竞争条件 - 如果在 os.path.existsos.makedirs 调用之间创建目录,则 os.makedirs 将失败并返回 OSError。不幸的是,一揽子OSError并继续不是万无一失的,因为它会忽略由于其他因素导致的目录创建失败,例如权限不足、磁盘已满等。

            一种选择是捕获OSError 并检查嵌入的错误代码(请参阅Is there a cross-platform way of getting information from Python’s OSError):

            import os, errno
            
            try:
                os.makedirs(directory)
            except OSError as e:
                if e.errno != errno.EEXIST:
                    raise
            

            另外,可能还有第二个os.path.exists,但假设另一个人在第一次检查后创建了目录,然后在第二次检查之前将其删除——我们仍然可能被愚弄。

            根据应用程序,并发操作的危险可能大于或小于文件权限等其他因素带来的危险。在选择实现之前,开发人员必须更多地了解正在开发的特定应用程序及其预期环境。

            现代版本的 Python 通过公开 FileExistsError(在 3.3+ 中)对这段代码进行了相当大的改进...

            try:
                os.makedirs("path/to/directory")
            except FileExistsError:
                # directory already exists
                pass
            

            ...并允许a keyword argument to os.makedirs called exist_ok(在 3.2+ 中)。

            os.makedirs("path/to/directory", exist_ok=True)  # succeeds even if directory exists.
            

            【讨论】:

              【解决方案13】:

              两件事

              1. 检查目录是否存在?
              2. 如果没有,请创建一个目录(可选)。
              import os
              dirpath = "<dirpath>" # Replace the "<dirpath>" with actual directory path.
              
              if os.path.exists(dirpath):
                 print("Directory exist")
              else: #this is optional if you want to create a directory if doesn't exist.
                 os.mkdir(dirpath):
                 print("Directory created")
              

              【讨论】:

              • 如果您要这样做,那么为什么不直接使用 os.mkdir() 并捕获(并忽略)FileExistsError。您的示例有一个检查时间/使用时间竞赛。检查 dirpath 是否存在和如果不存在则采取行动之间存在非零延迟。在那个时候,其他人可能会在 dirpath 上创建一个对象,无论如何你都必须处理这个异常。
              • @AdamHawes,解决方案基于被询问的查询,该查询专门询问“查找目录是否存在”,一旦验证了`if os.path.exists`,它是由编码人员决定进一步的程序,`os.mkdir` 只是一个假设性操作,因此我在代码中提到它作为一个选项。
              【解决方案14】:

              以下代码检查代码中引用的目录是否存在,如果它在您的工作场所不存在,则创建一个:

              import os
              
              if not os.path.isdir("directory_name"):
                  os.mkdir("directory_name")
              

              【讨论】:

                猜你喜欢
                • 2023-03-09
                • 2012-09-12
                • 2011-02-15
                • 2023-02-22
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多