在目录的每个子文件夹中创建一个文件夹?

2024-10-01 15:30:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想制作这样一个文件夹:

import os
rootfolder = r'C:\Users\user\Desktop\mainf'
for path, subdirs, files in os.walk(rootfolder):
    for i in subdirs:
        os.mkdir('newfolder')

mainf有100个子文件夹是空的。我想在每个文件夹中创建一个名为new folder的文件夹。上面的代码不起作用。你知道吗


Tags: pathinimport文件夹forosfilesusers
2条回答

我想试试os.makedirs(path/to/nested/new/directories, exist_ok=True)。你知道吗

这将使一个目录和所有必要的目录之间。你知道吗

另外,当你遍历一个目录时,要查看os.scandir(path/to/dir),因为它返回了这些非常方便使用的目录对象(例如,有绝对路径,说它是否存在,说它是否是一个文件/目录,等等)

os.mkdir('newfolder')尝试在当前目录中创建newfolder,而不考虑循环变量。你知道吗

您需要首先加入root&subdir,检查它是否已经存在(以便可以多次运行),并根据需要创建:

full_path_to_folder = os.path.join(path,i,'newfolder')
if not os.path.exists(full_path_to_folder):
   os.mkdir(full_path_to_folder)

在评论中讨论之后,这似乎是可行的,但将毫无用处地重复。path包含扫描时的目录路径,因此不需要内部循环。只需忽略walk产生的最后两个参数:

for path, _, _ in os.walk(rootfolder):
    full_path_to_folder = os.path.join(path,'newfolder')
    if not os.path.exists(full_path_to_folder):
       os.mkdir(full_path_to_folder)

相关问题 更多 >

    热门问题