在Python中,你可以使用 `os` 模块来创建目录。以下是创建目录的基本步骤和示例代码:
1. 导入 `os` 模块。
2. 使用 `os.path.exists` 函数检查目录是否已经存在。
3. 如果目录不存在,使用 `os.makedirs` 函数创建目录。`os.makedirs` 可以创建多级目录,如果父目录不存在,它会自动创建它们。
下面是一个简单的示例代码,展示了如何使用 `os` 模块创建目录:
import os
def create_directory(path):
去除路径字符串两端的空白字符和尾部反斜杠
path = path.strip().rstrip("\\")
检查路径是否存在
is_exists = os.path.exists(path)
如果不存在,则创建目录
if not is_exists:
os.makedirs(path)
print(f"Directory '{path}' created successfully.")
return True
else:
print(f"Directory '{path}' already exists.")
return False
定义要创建的目录路径
directory_path = "new_directory"
调用函数创建目录
create_directory(directory_path)
请注意,如果路径中包含文件,`os.makedirs` 会抛出异常。如果你需要处理这种情况,可以使用 `os.path.isfile` 函数检查路径是否为文件,或者使用 `os.path.isdir` 函数检查路径是否为目录。