美文网首页
python 判断文件夹是否存在 并创建

python 判断文件夹是否存在 并创建

作者: 一只失去梦想的程序猿 | 来源:发表于2019-05-16 18:43 被阅读0次

参数为路径,先判断路径文件是否存在,然后尝试直接新建文件夹,如果失败,说明路径是多层路径(还可能有别的原因,这里一般情况够用了),所以用makedirs创建多层文件夹。

import os
def createFile(filePath):
    if os.path.exists(filePath):
        print('%s:存在'%filePath)
    else:
        try:
            os.mkdir(filePath)
            print('新建文件夹:%s'%filePath)
        except Exception as e:
            os.makedirs(filePath)
            print('新建多层文件夹:%s' % filePath)

path1=os.getcwd()+'/1'
createFile(path1)

path2=os.getcwd()+'/2/3'
createFile(path2)

相关文章

网友评论

      本文标题:python 判断文件夹是否存在 并创建

      本文链接:https://www.haomeiwen.com/subject/zqdwaqtx.html