如何检查目录是否存在?


当前回答

有一个方便的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。不同之处在于,它将每个路径都视为字符串(path是str的子类),因此如果某个函数需要字符串,则可以轻松地将其传递给path对象,而无需将其转换为字符串。

例如,这对Django和settings.py非常有用:

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

其他回答

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

两件事

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

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

Python 3.4在标准库中引入了pathlib模块,它提供了一种面向对象的方法来处理文件系统路径。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

Python 2.7上也可以通过PyPi上的pathlib2模块获得Pathlib。

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

os.path.isdir("directory")

如果指定的目录可用,它将为布尔值true。

os.path.exists("directoryorfile")

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

检查路径是否为目录;

os.path.isdir(“目录路径”)

如果路径为directory,则返回布尔值true

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

import os.path
from os import path

步骤2:使用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()–如果路径为File,则返回True。os.path.isdir()–如果路径为Directory,则返回True。pathlib.Path.exists()–如果路径或目录确实存在,则返回True。(在Python 3.4及以上版本中)

文章参考:如何检查Python中是否存在目录?