3

I am trying to create folders using the following code. Something is not correct and leads to error:

"TypeError: 'str' object is not callable"

import os, sys

a= [4,3,2,1]
print len(a)
for idx in range (len(a)):

    newpath = r'E:\test\tool\folder_%s'(idx) 
    if not os.path.exists(newpath): os.makedirs(newpath)

Using os.makedirs I can create folders. However, I am not able to suffix those folders in a loop. Any ideas can be helpful. Thanks.

user741592
  • 773
  • 3
  • 7
  • 23
  • 3
    I think you forgot a `%` after the string before `(idx)`. – squiguy Apr 24 '13 at 06:57
  • Sorry. That was too dumb of me. Please disregard this question. The orignal code is big and I seem to have overlooked that % accidently got deleted – user741592 Apr 24 '13 at 07:01
  • 3
    That's a pretty strange way to loop through 0,1,2,3. – wim Apr 24 '13 at 07:02
  • Please see this http://stackoverflow.com/questions/273192/python-best-way-to-create-directory-if-it-doesnt-exist-for-file-write since your code has a potential race condition – jamylak Apr 24 '13 at 07:22

4 Answers4

5
import os, sys

a= [4,3,2,1]
print len(a)
for idx in range (len(a)):

    newpath = ((r'E:\test\tool\folder_%s') % (idx)) 
    if not os.path.exists(newpath): os.makedirs(newpath)

Try that, if it helps, accept the answer, if not leave a comment and I'll delete it.

hd1
  • 30,506
  • 4
  • 69
  • 81
1
newpath = r'E:\test\tool\folder_%s' % (idx) 
Asterisk
  • 3,436
  • 2
  • 32
  • 52
1

I think the preferred way to make strings is to use the format method.

newpath = 'E:\test\tool\folder_{0}'.format(idx)
squiguy
  • 29,170
  • 6
  • 49
  • 56
1

This code will create the folder with name client_1001-test to client_1500-test

import os, sys

for i in range(1001, 1500):
    newpath = ((r'/tmp/fileSet/client_%s-test') % (i)) 
    if not os.path.exists(newpath): os.makedirs(newpath)
Vanji
  • 1,686
  • 14
  • 23