Python文件夹操作

如何使用python 新建文件夹以及递归创建文件夹

  1. os.mkdir
    使用python创建文件夹,通常使用os.mkdir方法,在使用这个方法时有几个小的细节需要注意,假设你的代码是这样编写的
import os
os.mkdir('/dir_1/dir_2/dir_3')

你需要保证/dir_1/dir_2 是存在的,否则将引发FileNotFoundError,如果/dir_1/dir_2/dir_3 已经存在,又会引发FileExistsError,通常,我会使用os.path.exists方法判断关键的目录是否已经存在,来决定是否新建文件夹。

  1. os.makedirs
    os.makedirs 可以视为os.mkdir的升级版本,它以递归的方式创建文件夹,如果dir_1不存在,就先创建dir_1,而后递归创建剩余的文件夹,这样就不存在FileNotFoundError;如果想要创建的目录已经存在,也没有关系,设置exist_ok = True, 就不会引发FileExistsError
import os
os.makedirs('./1/2/3/4/5', exist_ok=True)

这两行代码你可以执行多次,不会有任何错误或异常

def create_dir(path):
'''
When a string is given directly instead of a path,
a dir will be created under the runtime folder
'''
import shutil
import os
try:
shutil.rmtree(path, ignore_errors=True)
os.makedirs(path, exist_ok=True)
except Exception as E:
print(E)
posted @   道友请留步W  阅读(96)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示