在Python中,你可以使用 `os` 模块来创建目录。以下是创建目录的基本步骤和示例代码:
1. 导入 `os` 模块。
2. 确定要创建的目录路径。
3. 使用 `os.mkdir` 函数创建单个目录。
4. 如果需要创建多层目录,可以使用 `os.makedirs` 函数。
下面是一个简单的示例代码,展示了如何使用 `os.mkdir` 创建一个目录:
```python
import os

指定要创建的新目录的名称
new_directory = "my_new_directory"
检查目录是否已经存在
if not os.path.exists(new_directory):
如果不存在,则创建目录
os.mkdir(new_directory)
print(f"Directory '{new_directory}' created successfully.")
else:
print(f"Directory '{new_directory}' already exists.")
如果你需要创建多级目录,并且父目录不存在,可以使用 `os.makedirs`:```pythonimport os
指定要创建的多级目录路径
dir_path = "path/to/your/directory"
检查路径中的每个目录是否存在,如果不存在则创建
os.makedirs(dir_path, exist_ok=True) exist_ok=True 表示如果目录已存在则不抛出异常
print(f"Directories in '{dir_path}' created successfully.")
请注意,`os.mkdir` 只会创建最底层的目录,如果父目录不存在,则会创建失败。而 `os.makedirs` 可以创建多级目录,如果路径中的任何一级目录不存在,它都会递归地创建它们。
