I want to create subfolders in already existing subfolders. For example, I have a rootdir with about 50 subfolders in it. In each subfolder I want to create about 5-6 new folders depending on the filename in the subfolder. Confusing? YeahIknow.. I think I know how to create new subfolders and naming them so I'm just wondering about how to walk between folders.

I want to create subfolders in already existing subfolders.

Use os.makedirs() to make directories.

I'm just wondering about how to walk between folders.

Use os.walk() or os.chdir() to move between directories.

Comments
Thorough

Well, this code creates new folders depending on the file name, but it does'nt care of which folder the file is in. I would like to walk through the subfolders in the rootdir and make new folders in every subfolder..

def separateToFolders(srcDir, destDir):
    for path, dirs, files in os.walk(srcDir):
            for fname in files:

                if 'D' in fname[2]:
                    subdir = os.path.join(destDir, 'Dep')
                else:
                    pass
                if 'H' in fname[2]:
                    subdir = os.path.join(destDir, 'Hal')
                else:
                    pass            

                if not os.path.isdir(subdir):
                    os.makedirs(subdir)

                shutil.move(os.path.join(path, fname), subdir)

I also need to move the files in the subfolder to new folder created within the subfolder. And also, my code just handle the first subfolder and doesnt walk through all of the subfolders.

I dont understand why this doesnt work:

def separateToFolders(destDir):
    outputList = []
    for path, dirs, files in os.walk(destDir):
        for m in dirs:
            outputList.append(os.path.join(path, m))
            name = outputList[0]
            for fname in files:

                if 'D' in fname[2]:
                    subdir = os.path.join(namn, 'Dep')
                else:
                    pass
                if 'H' in fname[2]:
                    subdir = os.path.join(namn, 'Hal')
                    print(subdir)
                else:
                    pass            

                if not os.path.isdir(subdir):
                    os.makedirs(subdir)

                shutil.move(os.path.join(path, fname), subdir)

can someone pleaz help me!?

This article has been dead for over six months. Start a new discussion instead.