You need to enable JavaScript to run this app. 如何使用Python判断文件夹是否存在并自动创建不存在的文件夹
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python判断文件夹是否存在并自动创建不存在的文件夹

Python 文件夹存在性校验与自动创建方案

Python 开发过程中,如需判断目标文件夹是否存在,且在文件夹不存在时自动创建对应目录,可参考如下实现代码:

import os
from datetime import datetime

file_path = "F:/TEST--"
if os.path.exists(file_path):
    os.rmdir(file_path)
    os.makedirs(file_path + datetime.now().strftime('%Y-%m-%d'))
else:
    os.makedirs(file_path + datetime.now().strftime('%Y-%m-%d'))

补充注意事项

  • 代码中使用的os.rmdir仅支持删除空文件夹,如需删除非空目录,可替换为shutil.rmtree方法(使用前需提前导入shutil库)
  • os.makedirs默认支持递归创建路径中所有不存在的父级目录,无需额外单独判断父级路径的存在状态

内容的提问来源于stack exchange,提问作者DevLeb2022

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 23:54:03