How to create directories and sub directories efficiently and elegantly in Python 2.7? -
i trying create bunch of directories , sub directories @ specific location in pc. process this:
- check if there's directory same directory name. skip if so.
- if not, create directory , pre-defined sub directories under directory.
this code came using os
module:
def test(): main_dir = ["foldera", "folderb"] common_dir = ["subfolder1", "subfolder2", "subfolder3"] dir1 in main_dir: if not os.path.isdir(dir1): dir2 in common_dir: os.makedirs("%s/%s" %(dir1,dir2))
i wondering if there's better way same task (probably shorter, more efficient , more pythonic)?
python follows philosophy
it better ask forgiveness ask permission.
so rather checking isdir
, catch exception thrown if leaf directory exists:
def test(): main_dir = ["foldera", "folderb"] common_dir = ["subfolder1", "subfolder2", "subfolder3"] dir1 in main_dir: dir2 in common_dir: try: os.makedirs(os.path.join(dir1,dir2)) except oserror: pass
you can replace string interpolation "%s/%s" %(dir1,dir2)
os.path.join(dir1, dir2)
another more succinct way cartesian product instead of using 2 nested for-loops:
for dir1, dir2 in itertools.product(main_dir, common_dir): try: os.makedirs(os.path.join(dir1,dir2)) except oserror: pass
Comments
Post a Comment