user10663146
user10663146

Reputation: 45

Make a folder in each subfolder in a directory?

I want to make a folder like this:

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 has 100 subfolders that are empty. I want to make a folder called new folder in every one of them. The code above doesn't work.

Upvotes: 3

Views: 484

Answers (2)

O.rka
O.rka

Reputation: 30677

I would try os.makedirs(path/to/nested/new/directories, exist_ok=True).

This will make a directory and all of the necessary directories in between.

Also, look into os.scandir(path/to/dir) when you iterate through a directory because it returns these directory objects that are really convenient to use (e.g. has the absolute path, says if it exists, says if it is a file/dir, etc.)

Upvotes: 1

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

os.mkdir('newfolder') tries to create newfolder in the current directory regardless of the loop variables.

You need to join with root & subdir first, check that it doesn't already exist (so you can run it more than once) and create if needed:

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)

after a discussion in comments, it appears that this works but will iterate uselessly. path contains the directory paths when scanning, so no need for the inner loop. Just ignore the last 2 arguments that walk yields and do:

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)

Upvotes: 4

Related Questions