在Python中,如何检测一个目录是否存在?如果不存在,如何创建它?请给出代码示例和说明。
import os
# 检查目录是否存在
directory_path = 'example_directory'
if not os.path.exists(directory_path):
# 如果目录不存在,则创建目录
os.makedirs(directory_path)
print(f'目录 {directory_path} 已创建')
else:
print(f'目录 {directory_path} 已存在')
详细说明
-
检测目录是否存在:
- 使用
os.path.exists()方法可以检查指定路径是否存在。该方法接收一个路径字符串作为参数,返回一个布尔值,表示路径是否存在。 - 例如,
os.path.exists('example_directory')会返回True或False,分别表示目录是否存在。
- 使用
-
创建目录:
- 使用
os.makedirs()方法可以创建目录。如果目录的父目录不存在,os.makedirs()也会递归创建所有缺失的父目录。 - 例如,
os.makedirs('example_directory')会创建名为example_directory的目录。
- 使用
示例代码解释
- 首先定义一个目录路径
directory_path,假设其值为example_directory。 - 通过
os.path.exists()检查该路径是否存在。如果不存在,调用os.makedirs()创建目录;如果存在,则打印目录已存在的消息。
其他注意事项
- 权限问题:如果当前用户没有权限在指定路径下创建目录,会抛出
PermissionError异常。因此,实际使用时可能需要处理权限问题。 - 路径格式:路径可以是相对路径(如
example_directory)或绝对路径(如C:/Users/username/example_directory)。 - 目录已存在的情况:如果目录已存在,直接调用
os.makedirs()会抛出FileExistsError异常。为了避免这个问题,通常会在调用前检查路径是否存在。