首页 > 解决方案 > 如何在python中一次为windows创建多个文件夹

问题描述

嘿,我是编程新手,谁能帮我指出正确的方向?我正在尝试为一个排序程序同时创建多个文件夹,以检查该文件夹是否存在,以及它是否没有以文件类型命名的文件夹对其进行排序。我正在查找它并找到了一些代码,但我不明白它在计算机上的哪个位置写入。这是我在网上找到的代码:

import os

# define the name of the directory to be created
path = "/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)

标签: python

解决方案


To create multiple folders create a list of folder names and set the path to the parent-folder:

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)

推荐阅读