python语言,如何在已有的文件夹下创建新的文件夹?

2024-07-03 02:36:13
推荐回答(2个)
回答1:

可以使用贺正os包的mkdir函数来创建新的文件夹。

mkdir函数接受一个禅首悔参数path指定新建文件夹的路径,示例代码如下:

import os

cur_dir = 'D:\curdir'
folder_name = 'baiduzhidao'
if os.path.isdir(cur_dir):
    os.mkdir(os.path.join(cur_dir, folder_name))

为了确保已有的文件夹真实存在,示例代码中使用了os.path.isdir函数判断已有芹做文件夹的路径是否正确。

新的文件夹的路径可以由os.path.join函数,将已有文件夹的路径和新建文件夹文件名连接起来得到。由于Windows操作系统和Linux操作系统,路径的连接符不同,使用os.path.join连接能够确保同时在不同的操作系统中正常工作。

回答2:

year = "时间"

month = "月份"

day = "天数"

path = "族态D:\\Env\\bair\\"

title_year = str(year)

title_month = str(month)

title_day = str(day)

new_path_year = os.path.join(path,title_year)

if not os.path.isdir(new_path_year):

os.makedirs(new_path_year)

new_path_month = os.path.join(new_path_year,title_month)

if not os.path.isdir(new_path_month):

os.makedirs(new_path_month)

new_path_day = os.path.join(new_path_month,title_day)

if not os.path.isdir(new_path_day)

根据具体问题类型,进行步骤拆解/原因原理分析/内容拓展扒稿等。
具体步骤如下:/导致这种情况的原因主要是……兆此源