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

Dav*_*542 1048 python directory

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

>>> os.direxists(os.path.join(os.getcwd()), 'new_folder')) # in pseudocode
True/False
Run Code Online (Sandbox Code Playgroud)

phi*_*hag 1613

您正在寻找os.path.isdir,或者os.path.exists您不关心它是文件还是目录.

例:

import os
print(os.path.isdir("/home/el"))
print(os.path.exists("/home/el/myfile.txt"))
Run Code Online (Sandbox Code Playgroud)

  • 您可以将函数传递给其他函数,例如`map`,但在一般情况下,您可以使用参数和括号调用函数.此外,您的示例中还有一些拼写错误.大概是指`filter(os.path.isdir,['/ lib','/ usr/lib','/ usr/local/lib'])`. (10认同)
  • @syedrakib虽然括号可用于表示对象是可调用的,但这在Python中没用,因为即使类也是可调用的.此外,函数是Python中的第一类值,您可以使用*而不使用*括号表示法,例如`existing = filter(os.path.isdir(['/ lib','/ usr/lib','的/ usr/local/lib目录'])` (4认同)
  • 此外,如果你只关心它是否是一个文件,还有`os.path.isfile(path)`. (4认同)
  • 请注意,在某些平台上,如果文件/目录存在,它们将返回false,但是也会发生读取许可权错误。 (2认同)

Kir*_*ser 71

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

  • 或者使用 pathlib: `Path(path).mkdir(parents=True, exit_ok=True)` 在一个操作中创建一个嵌套路径。 (4认同)

joe*_*lom 54

蟒3.4引入pathlib模块到标准库,它提供了一个面向对象的方法来处理的文件系统的路径:

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
Run Code Online (Sandbox Code Playgroud)

Pathlib也可以通过PyPi上的pathlib2模块在 Python 2.7 上使用.


aga*_*rs3 33

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

  • 这不会检查路径是否是目录. (21认同)
  • 好决定.其他人指出,`os.path.isdir`将实现这一目标. (7认同)
  • @Gabriel然后应该在答案中明确这实际上做了什么. (4认同)
  • 如果您明白这不能回答这个问题,为什么不删除答案呢? (3认同)
  • @CamilStaps这个问题被浏览了354000次(到目前为止).这里的答案不仅适用于OP,也适用于任何因任何原因可能来到这里的人.aganders3的答案是相关的,即使它没有直接解决OP的问题. (3认同)

sks*_*mik 23

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

import os

if not os.path.isdir("directory_name"):
    os.mkdir("directory_name")
Run Code Online (Sandbox Code Playgroud)


Viv*_*han 20

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

os.path.isdir("directory")
Run Code Online (Sandbox Code Playgroud)

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

os.path.exists("directoryorfile")
Run Code Online (Sandbox Code Playgroud)

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

检查路径是否为目录;

os.path.isdir("directorypath")

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

  • 这与旧的最佳答案完全多余。 (2认同)

AlG*_*AlG 10

如:

In [3]: os.path.exists('/d/temp')
Out[3]: True
Run Code Online (Sandbox Code Playgroud)

可能会折腾到一个os.path.isdir(...)可以肯定的.


Tyl*_* A. 9

只是为了提供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
Run Code Online (Sandbox Code Playgroud)


小智 7

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
Run Code Online (Sandbox Code Playgroud)

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


fra*_*ank 7

如果目录不存在,您可能还想创建该目录。

Source,如果它仍然存在于 SO 上。

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

在 Python 上?3.5、使用pathlib.Path.mkdir

from pathlib import Path
Path("/my/directory").mkdir(parents=True, exist_ok=True)
Run Code Online (Sandbox Code Playgroud)

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

尝试os.path.exists,并os.makedirs为创作考虑。

import os
if not os.path.exists(directory):
    os.makedirs(directory)
Run Code Online (Sandbox Code Playgroud)

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

一种选择是捕获OSError并检查嵌入的错误代码(请参阅是否有一种跨平台的方式从 Python 的 OSError 获取信息):

import os, errno

try:
    os.makedirs(directory)
except OSError as e:
    if e.errno != errno.EEXIST:
        raise
Run Code Online (Sandbox Code Playgroud)

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

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

现代版本的 Python 通过公开FileExistsError(在 3.3+ 中)...

try:
    os.makedirs("path/to/directory")
except FileExistsError:
    # directory already exists
    pass
Run Code Online (Sandbox Code Playgroud)

...并允许调用关键字参数os.makedirsexist_ok(在 3.2+ 中)。

os.makedirs("path/to/directory", exist_ok=True)  # succeeds even if directory exists.
Run Code Online (Sandbox Code Playgroud)


Moh*_*had 6

步骤 1:导入 os.path 模块
\n在运行代码之前导入 os.path 模块。

\n
import os.path\nfrom os import path\n
Run Code Online (Sandbox Code Playgroud)\n

步骤2:使用path.exists()函数
\npath.exists()方法用于查找文件是否存在。

\n
path.exists("your_file.txt")\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n
path.isfile(\'your_file.txt\')\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n
path.isdir(\'myDirectory\')\n
Run Code Online (Sandbox Code Playgroud)\n

这是完整的代码

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

Python 3.4 的 pathlibPath.exists()

\n

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

\n
import pathlib\nfile = pathlib.Path("your_file.txt")\nif file.exists ():\n    print ("File exist")\nelse:\n    print ("File not exist")\n
Run Code Online (Sandbox Code Playgroud)\n
    \n
  • os.path.exists() \xe2\x80\x93 如果路径或目录确实存在,则返回 True。
  • \n
  • os.path.isfile() \xe2\x80\x93 如果路径是文件,则返回 True。
  • \n
  • os.path.isdir() \xe2\x80\x93 如果路径是目录,则返回 True。
  • \n
  • pathlib.Path.exists() \xe2\x80\x93 如果路径或目录确实存在,则返回 True。(在Python 3.4及以上版本中)
  • \n
\n

引用的文章如何检查 Python 中的目录是否存在?

\n


Job*_*ive 5

#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')
Run Code Online (Sandbox Code Playgroud)

  • 您正在打印*'已创建新目录'*,但您不知道。如果您没有创建目录的权限怎么办?您将打印*“已创建新目录” *,但事实并非如此。会的。 (8认同)
  • python内置了创建目录的功能,因此最好使用os.makedirs('mydir')而不是os.system(...) (5认同)

Max*_*ysh 5

有一个方便的Unipath模块。

>>> from unipath import Path 
>>>  
>>> Path('/var/log').exists()
True
>>> Path('/var/log').isdir()
True
Run Code Online (Sandbox Code Playgroud)

您可能需要的其他相关资料:

>>> 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
Run Code Online (Sandbox Code Playgroud)

您可以使用 pip 安装它:

$ pip3 install unipath
Run Code Online (Sandbox Code Playgroud)

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

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

# settings.py
BASE_DIR = Path(__file__).ancestor(2)
STATIC_ROOT = BASE_DIR + '/tmp/static'
Run Code Online (Sandbox Code Playgroud)


Uda*_*ran 5

两件事情

  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")
Run Code Online (Sandbox Code Playgroud)