如何在 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)


萧十郎
浏览 154回答 2
2回答

慕码人8056858

要创建多个文件夹,请创建文件夹名称列表并设置父文件夹的路径:import os# define the name of the directory to be createdpath = 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)

慕斯709654

也试试这个import ospath = "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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python