I am new to python and I am looking for a way to create subfolders within subfolders. My file tree looks like this:
>> Main Folder
>> Folder a
>> Folder 1
>> Folder 2
>> Folder b
>> Folder 1
>> Folder 2
I am looking for a way to create a new folder in the bottom most level (folder 1 and folder 2).
I've tried using os.walk and os.path, like this
for dirpath, subdirs, files in os.walk(current_path):
for subdir in subdirs:
filePath = os.path.abspath(subdir)
newFolder = (filePath + "/new")
if not os.path.exists(newFolder):
os.mkdir(newFolder)
But this only creates the new folder in the second level (Folder a and Folder b), then gives me the error:
FileNotFoundError: [Errno 2] No such file or directory: '/Users/diunt-02/Desktop/Brown_Brothers/TEST/new/new'
I think that the loop is making new folders, and the os.walk can't find a path to them. Are there any suggestions for getting os.walk to move into the next level down and create a folder there?
If you're just trying to create a subdirectory in every grandchild of the root directory, using os.walk
is just going to make things more confusing. I'll explain why, but first, I'll explain the easier way.
Just explicitly loop two levels down:
for child in os.scandir(current_path):
if child.is_dir():
for grandchild in os.scandir(child.path):
newpath = os.path.join(grandchild.path, 'new')
os.path.mkdir(newpath)
Now, why is your existing code broken?
walk
walks the whole tree. It visits the root, and the children, and the grandchildren, and the great-grandchildren, and even the new grandchildren that you create while you're in the middle of walking.
For example, try this:
for dirpath, _, _ in os.walk(current_path):
print(dirpath)
What you get is:
.
./Folder b
./Folder b/Folder 2
./Folder b/Folder 1
./Folder a
./Folder a/Folder 2
./Folder a/Folder 1
It's mixing all the different "levels" together. But you don't want to do the same thing at every level. You only want to create new directories in the grandchildren, not the children, and not the great-grandchildren, and especially not any descendants that you create along the way.
Sure, you can try to keep track of the level as you go up and down, or you can probably see how you could recreate it on the fly from the dirpath
, but why? If you want to do something exactly 2 levels down, don't loop over all levels and then test for level 2, just go 2 levels down.