为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 python 中一次为 Windows 创建多个文件夹

如何在 python 中一次为 Windows 创建多个文件夹

萧十郎 2023-05-23 16:16:23
嘿,我是编程新手,谁能帮我指明正确的方向?我正在尝试为一个排序程序将多个文件夹放在一个文件夹中,几乎是在检查文件夹是否存在,以及它是否不以文件类型命名的文件夹进行排序。我在查找它并找到了一些代码,但我不明白它正在写入计算机的哪个位置。这是我在网上找到的代码:import os# define the name of the directory to be createdpath = "/tmp/year/month/week/day"try:    os.makedirs(path)except OSError:    print ("Creation of the directory %s failed" % path)else:    print ("Successfully created the directory %s" % path)
查看完整描述

2 回答

?
慕码人8056858

TA贡献1803条经验 获得超6个赞

要创建多个文件夹,请创建文件夹名称列表并设置父文件夹的路径:


import os


# define the name of the directory to be created

path = r"D:\test"

lst_folders = [r"Folder_A", r"Folder_B", r"Folder_C"]


for new_folder in lst_folders:

    print(new_folder)

    path_new = os.path.join(path, new_folder)

    

    try:

        os.makedirs(path_new)

    except OSError:

        print ("Creation of the directory %s failed" % path)

    else:

        print ("Successfully created the directory %s" % path)


查看完整回答
反对 回复 2023-05-23
?
慕斯709654

TA贡献1840条经验 获得超5个赞

也试试这个


import os


path = "parent"


for new in range(5):

    print(f'{path}/child_{new}')

    try:

        os.makedirs(f'{path}/child_{new}')

    except OSError:

        print ("Creation of the directory %s failed" % path)

    else:

        print ("Successfully created the directory %s" % path)


查看完整回答
反对 回复 2023-05-23
  • 2 回答
  • 0 关注
  • 145 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信