Python只需要引入os模块,使用相关函数即可实现目录的创建。
主要涉及到三个函数:
1、os.path.exists(path) 判断一个目录是否存在
2、os.makedirs(path) 多层创建目录
3、os.mkdir(path) 创建目录
import os
def mkdir(pathStr):
# 去除首位空格
path = pathStr.strip()
# 判断路径是否存在,True表示存在,False表示不存在
isExists = os.path.exists(path)
# 判断结果
if not isExists:
# 如果不存在则创建目录
os.makedirs(path)
print(path + " 创建成功")
return True
else:
# 如果目录存在则不创建
return False
# 定义要创建的目录
mkpath = "E:\\demo\\web"
# 调用函数
mkdir(mkpath)
os.mkdir(path)函数和os.makedirs(path)函数之间的区别:当父目录不存在的时候os.mkdir(path)不会创建,os.makedirs(path)则会创建父目录