Making hierarchy of folders using Python


Suppose you want to make many folders aka directories for some purposes. Maybe you need to make many folders in a relative’s computers? Maybe you want to make many folders with same pattern in the names? Maybe someone has a habit of deleting files or formatting his hard drive and you have the responsibility of making a basic folder hierarchy>

I posted how to delete files so I thought to add one to make files also.

The hierarchy of directories that I am making is like this. Every indent means a subdirectory of the previous unindented one.

./project_euler
    ./001_050
    ./051_100
    ...
    ./401_450
./codechef
    ./easy
    ./medium
    ./hard
./spoj
./functions
./utilities

I made this script to learn Python mainly but it can be used to do same task of creating directories again and again easily. There are alternatives in Unix/Linux but in Windows it might be the easiest way.

#! python3
import os

TOP_LEVEL = ('spoj', 'functions', 'utilities', '_testing')
EULER_HIGHEST = 450
CODECHEF_FOL = ('easy', 'medium', 'hard')

def safe_make_folder(i):
    '''Makes a folder and its parent if not present'''
    try:
        os.makedirs(i)
    except:
        pass

def make_top_level():
    '''Makes folders with no subdirectories'''
    for i in TOP_LEVEL:
        safe_make_folder(i)

def make_euler_folders():
    '''Makes euler and its subdirectories'''
    for j in (os.path.join('project_euler', '{:03}_{:03}'.format(i, i + 49))
              for i in range(1,EULER_HIGHEST, 50)):
        safe_make_folder(j)

def make_codechef_folders():
    '''Makes codechef and its subdirectories'''
    for i in CODECHEF_FOL:
        safe_make_folder(os.path.join('codechef', i))

def main():
    make_top_level()
    make_euler_folders()
    make_codechef_folders()

if __name__ == "__main__":
    main()

This script’s comments are self-explanatory. Any questions? Just ask in the comments?

Advertisements