ChatGPT解决这个技术问题 Extra ChatGPT

如何检查 Python 中是否存在目录?

如何检查目录是否存在?

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

M
Mateen Ulhaq

仅对目录使用 os.path.isdir

>>> import os
>>> os.path.isdir('new_folder')
True

对文件和目录使用 os.path.exists

>>> import os
>>> 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')))
j
joelostblom

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 我对答案的第二部分进行了详细说明。
K
Kirk Strauser

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


如果你想创建它os.path.isdir(path) or os.makedirs(path)
或者使用 pathlib: Path(path).mkdir(parents=True, exist_ok=True) 在一个操作中创建一个嵌套路径。
a
aganders3

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


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

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

os.path.isdir("directory")

它将给出 boolean true 指定的目录可用。

os.path.exists("directoryorfile")

如果指定的目录或文件可用,它将给出布尔值 true。

检查路径是否为目录;

os.path.isdir("directorypath")

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


对于较旧的顶级答案,这完全是多余的。
R
RanRag

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


s
sksoumik

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

import os

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

A
AlG

如:

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

可能会折腾一个os.path.isdir(...)来确定。


T
Tyler A.

只是为了提供 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对该问题的评论中提到的竞争条件吗?
N
Nathan

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

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)

如评论和其他地方所述,存在竞争条件 - 如果在 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.

E
Eric Leschinski

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


R
Ramapati Maurya
#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(...)
您正在打印“已创建新目录”,但您不知道。如果您没有创建目录的权限怎么办?您会打印“新目录已创建”,但事实并非如此。会吗。
G
Georgy

有一个方便的 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'

U
Uday Kiran

两件事情

检查目录是否存在?如果没有,请创建一个目录(可选)。

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` 只是一个假设动作,因此我在代码中提到它作为一个选项。
u
user8133129

第一步:导入 os.path 模块 在运行代码之前导入 os.path 模块。

import os.path
from os import path

第二步:使用 path.exists() 函数 path.exists() 方法用于查找文件是否存在。

path.exists("your_file.txt")

第 3 步:使用 os.path.isfile() 我们可以使用 isfile 命令来确定给定的输入是否为文件。

path.isfile('your_file.txt')

第 4 步:使用 os.path.isdir() 我们可以使用 os.path.dir() 函数来确定给定的输入是否是目录。

path.isdir('myDirectory')

这是完整的代码

    import os.path
    from os import path
    
    def main():
    
       print ("File exists:"+str(path.exists('your_file.txt')))
       print ("Directory exists:" + str(path.exists('myDirectory')))
       print("Item is a file: " + str(path.isfile("your_file.txt")))
       print("Item is a directory: " + str(path.isdir("myDirectory")))
    
    if __name__== "__main__":
       main()

pathlibPath.exists() 对于 Python 3.4

Pathlib 模块包含在 Python 3.4 及更高版本中,用于处理文件系统路径。 Python 使用面向对象的技术检查文件夹是否存在。

import pathlib
file = pathlib.Path("your_file.txt")
if file.exists ():
    print ("File exist")
else:
    print ("File not exist")

os.path.exists() - 如果路径或目录确实存在,则返回 True。

os.path.isfile() – 如果 path 是 File,则返回 True。

os.path.isdir() - 如果路径是目录,则返回 True。

pathlib.Path.exists() - 如果路径或目录确实存在,则返回 True。 (在 Python 3.4 及以上版本中)