如何在Python中查找目录是否存在 [英] How to find if directory exists in Python

查看:22
本文介绍了如何在Python中查找目录是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<预><代码>>>>os.direxists(os.path.join(os.getcwd()), 'new_folder')) # 伪代码真假

解决方案

您正在寻找 os.path.isdiros.path.exists 如果你不在乎无论是文件还是目录:

<预><代码>>>>导入操作系统>>>os.path.isdir('new_folder')真的>>>os.path.exists(os.path.join(os.getcwd(), 'new_folder', 'file.txt'))错误的

或者,您可以使用 pathlib:

 >>>从 pathlib 导入路径>>>路径('new_folder').is_dir()真的>>>(Path.cwd()/'new_folder'/'file.txt').exists()错误的

In the os module in Python, is there a way to find if a directory exists, something like:

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

解决方案

You're looking for os.path.isdir, or os.path.exists if you don't care whether it's a file or a directory:

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

Alternatively, you can use pathlib:

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

这篇关于如何在Python中查找目录是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆