如何检查目录是否存在?
当前回答
有一个方便的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'
其他回答
步骤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中是否存在目录?
是的,使用os.path.exists()。
如果目录不在,您可能还想创建该目录。
来源,如果它还在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.exists和os.makedirs调用之间创建目录,os.makedir将失败,并出现OSError。不幸的是,全面捕获OSError并继续并不是万无一失的,因为它会忽略由于其他因素(如权限不足、磁盘已满等)导致的目录创建失败。
一种选择是捕获OSError并检查嵌入的错误代码(请参阅是否有跨平台的方式从Python的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
…并允许os.makedirs使用名为exist_ok的关键字参数(在3.2+中)。
os.makedirs("path/to/directory", exist_ok=True) # succeeds even if directory exists.
仅对目录使用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
以下代码检查代码中引用的目录是否存在,如果您的工作场所中不存在,则会创建一个:
import os
if not os.path.isdir("directory_name"):
os.mkdir("directory_name")
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录