Search code examples
pythondirectorycreation

Using Python to create blank folders in users' directories


I have created a Python script to create new folders in users' directories. It works well however, if the program is run again, then for some reason it will make blank folders in the root directory. As an example

Root - Dave

  • Jim

  • Bob

After the program runs once

  • Dave

---- Science

---- English

---- Maths

  • Jim

---- Science

---- English

---- Maths

  • Bob

---- Science

---- English

---- Maths

After the program has run again (just incase a new user gets added) this happens

  • Science

  • English

  • Maths

  • Dave

---- Science

---- English

---- Maths

  • Jim

---- Science

---- English

---- Maths

  • Bob

---- Science

---- English

---- Maths

If the program is run then again, it works.

Any help would be appreciated.

Ta

Code is here:

import os

currentPath = os.getcwd()
folders = ["English","Science","Maths"]

directory_list = list()
for root, dirs, files in os.walk(currentPath, topdown=False):
    for name in dirs:
        directory_list.append(os.path.join(root, name))

        path = currentPath+"\\"+name

        for i in range(len(folders)):

            try:  
                os.makedirs(path+"/"+folders[i])
            except OSError:  
                print ("Creation of the directory %s failed" % path)
            else:  
                print ("Successfully created the directory %s " % path)

Solution

  • You should first check to see if the directory exists before creating a new on with the same name.

    import os
    
    currentPath = os.getcwd()
    folders = ["English","Science","Maths"]
    
    directory_list = list()
    for dir in os.listdir(currentPath):
    
        temp_path = currentPath+"\\"+dir
    
        if os.path.isdir(temp_path):
            for folder in folders:
                if not os.path.isdir(temp_path+"\\"+folder):
                    new_folder = temp_path+"\\"+folder
                    try:
                        os.makedirs(temp_path+"\\"+folder)
                    except OSError:  
                        print ("Creation of the directory %s failed" % new_folder)
                    else:  
                        print ("Successfully created the directory %s " % new_folder)
    

    I had to rewite a bit of the code, but I tested this and it works!

    I think writing to the var path was giving unintended behavior so I renamed the variable.