0

I have a directory with the following subdirs:

folder_001 to folder_100

However, I need to test as some directories may be missing. Is the following the best way to accomplish this. Seems a bit long winded.

>>> l = []
>>> for i in l:
...  for f in os.listdir('.'):
...   if not os.path.exists(i):
...    os.mkdir(i)
...

Thanks.

S1M0N_H
  • 109
  • 3
  • 9

3 Answers3

5
for i in xrange(1,101):
   name = 'folder_%03d' % (i)
   if not os.path.exists(name): 
      os.mkdir(name)
Steve Barnes
  • 27,618
  • 6
  • 63
  • 73
1
import shutil

for item in os.listdir('.'):
    if not os.path.exists(item):
        os.makedirs(item)
    else:
        shutil.rmtree(item)           #removes a tree with all subdirs!
        os.makedirs(item)
securecurve
  • 5,589
  • 5
  • 45
  • 80
0

more generic:

l = []
for f in os.listdir('.'):
    if f in l: l.remove(f)
for f in l:
    os.mkdir(f)

or:

l = []
dirs = os.listdir('.')
for f in l:
    if not f in dirs: os.mkdir(f)
Cesar
  • 707
  • 3
  • 13