每次想在新的位置输出文件时,都需要去自己新建几层的文件夹,这里记录一下如何让程序自动执行“若文件夹不存在则自动新建”:
import os
folder = folder_path
if not os.path.exists(folder_path): #判断是否存在文件夹如果不存在则创建为文件夹
os.makedirs(folder_path)
但是值得注意的是,如果出现报错:FileNotFoundError: [Errno 2] No such file or directory:
那么你的代码可能是os.makedir
,而不是os.makedirs
——
os.makedirs只能创建一级目录,而os.makedirs
可以创建点多级目录!
参考:python创建文件和文件夹