0

I am looking to iterate on items within an array using python and create folders for items.

The following is my format:

'0001': ['123101203', '1221231102136'], 
'0002': ['1681235932', '22612312303', '213412312341', '123123610116'], 
'0003': ['123408503']

What I am looking to do is to look through the Array and create Folders for each item and subfolders for each sub-item.

i.e. there is a 0001 folder, and within it there is a 1230101203 folder and a 1222.. folder , etc.

I was approaching it like the following:

sample = [Array]
for s in sample:       
   os.mkdir(n)
   os.chdir(n + '/')
        Create subfolders for each array item
   # os.chdir('../')
3
  • 1
    ... What's the question here? Commented Mar 9, 2015 at 18:41
  • will you go on this nested structure or it stops in 2d? Commented Mar 9, 2015 at 18:42
  • I am wondering how to loop through the array and through each of its items. I was thinking a nested structure makes sense Commented Mar 9, 2015 at 18:56

2 Answers 2

2

You'll have to add error handling for existing directories, but you can do the following in order to not have to worry about nested loops or building up the path:

from os import makedirs, path
from itertools import product, chain

data = {
    '0001': ['123101203', '1221231102136'],
    '0002': ['1681235932', '22612312303', '213412312341', '123123610116'],
    '0003': ['123408503']
}

dirs = chain(*list(product((k,), v) for k, v in data.items()))
for parent, sub in dirs:
    makedirs(path.join(parent, sub))
Sign up to request clarification or add additional context in comments.

2 Comments

This is great! If there are existing directories is there an easy way to overwrite it?
@user1982011: You can check for its existence beforehand (os.path.exists and os.path.isdir) and delete it using shutil.rmtree.
1

So pretty much what you want to do is a nested loop. As sample looks a bit like a dict, you have first to get the keys of the dict to access the lines of your "array".

for s in sample.keys(): 
   # mkfolder for 1st level; s is storing the key name
   for i in sample[s]:
       # do the rest of the folders

Of course you might need to build up the path, but this should be not a big issue as you have s and different i.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.