python os判断目录是否存在
时间: 2023-10-02 15:10:13 浏览: 28
在Python中,可以使用`os.path.exists()`函数来判断目录是否存在。该函数返回一个布尔值,如果目录存在则返回True,否则返回False。
以下是一个示例代码:
```python
import os
# 目录路径
dir_path = '/path/to/directory'
# 判断目录是否存在
if os.path.exists(dir_path):
print('目录存在')
else:
print('目录不存在')
```
其中,`/path/to/directory`为要判断的目录路径。如果该目录存在,则输出`目录存在`,否则输出`目录不存在`。
相关问题
python判断目录是否存在,不存在创建
你可以使用 Python 的 `os` 模块来判断目录是否存在,如果不存在则创建:
```python
import os
directory = 'path/to/directory'
if not os.path.exists(directory):
os.makedirs(directory)
print(f"Directory '{directory}' created successfully.")
else:
print(f"Directory '{directory}' already exists.")
```
在上面的代码中,我们首先指定要检查的目录路径。然后,使用 `os.path.exists()` 方法检查目录是否存在。如果目录不存在,我们使用 `os.makedirs()` 方法创建目录。最后,我们在控制台上打印一条消息,指示目录是否创建成功。
请注意,在使用 `os.makedirs()` 方法创建目录时,如果指定的目录路径的上级目录不存在,则会自动创建所有缺少的上级目录。
python 判断 目录 或文件是否存在
可以使用 Python 的 os 模块中的 path.exists() 方法来判断目录或文件是否存在。例如:
import os
if os.path.exists('/path/to/directory'):
print('目录存在')
else:
print('目录不存在')
if os.path.exists('/path/to/file'):
print('文件存在')
else:
print('文件不存在')
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)