Python mkdir 如果文件夹不存在,则创建它

371 阅读1分钟
  •        Python : 3.8.13
  •          OS : Windows 21H1
  •       Conda : 4.12.0
  •     PyCharm : 2022.1 (Community Edition)

代码

import os

config_dir = 'config'

if not os.path.exists(config_dir):
    os.mkdir(config_dir)
    print("创建文件夹")
else:
    print("文件夹已存在")

if not os.path.exists(config_dir):
    os.mkdir(config_dir)
else:
    print("文件夹已存在")

运行

D:\Develop\Anaconda3\envs\pyqtenv\python.exe C:/Users/admin/Desktop/pythonProject/main.py
创建文件夹
文件夹已存在

Process finished with exit code 0

学习推荐


Python具有开源、跨平台、解释型和交互式等特性,值得学习。
Python的设计哲学:优雅,明确,简单。提倡用一种方法,最好是只有一种方法来做一件事。
代码的书写要遵守规范,这样有助于沟通和理解。
每种语言都有独特的思想,初学者需要转变思维、踏实践行、坚持积累。