python判断目录是否存在,不存在创建
时间: 2024-01-11 16:16:18 浏览: 42
你可以使用 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 判断目录是否存在 如果不存在则创建
可以使用os模块中的path.exists()函数判断目录是否存在,如果不存在则使用os.mkdir()函数创建目录。
示例代码:
```python
import os
dir_path = '/path/to/directory'
if not os.path.exists(dir_path):
os.mkdir(dir_path)
print('目录创建成功!')
else:
print('目录已存在。')
```
其中,dir_path为目录路径,如果目录不存在则使用os.mkdir()函数创建目录。如果目录已经存在,则提示目录已存在。
python 判断文件夹是否存在,不存在则创建文件夹
可以使用Python的os模块来判断文件夹是否存在,如果不存在则创建文件夹。代码如下:
```python
import os
folder_path = "path/to/folder"
if not os.path.exists(folder_path):
os.makedirs(folder_path)
```
其中,`os.path.exists()`方法用于判断文件或文件夹是否存在,如果存在则返回True,否则返回False。`os.makedirs()`方法用于创建多级目录,如果已经存在则不会重复创建。