0

I need to create directories from for loop. I have a list.

a = [banana 1234, apple 456, orange 789]

And I need to create folders named by the numbers that are ending with numbers in list. for example.

C:\folder\1234; C:\folder\456

and so on.

code is

for length in atrinkta:
folder = re.findall(r'\d{9,}', length)
os.makedirs("D:/python_study/images/skelbimai/" + folder)

but I get an error "TypeError: cannot concatenate 'str' and 'list' objects" don't know what to do. Please someone help.

EDIT I tried your method 2nd time. After deleting created folder for whatever reason python gives me error

WindowsError: [Error 183] Cannot create a file when that file already exists: 'D:/python_study/images/skelbimai/'

2ndEdit

shaktimaan, now i get other error AttributeError: 'NoneType' object has no attribute 'group'. What does this mean?

K00764
  • 233
  • 1
  • 2
  • 6
  • You asked on my answer (which I deleted) how to avoid creating a dir that already exists (or was already created). [Just check if the directory exists before creating it](http://stackoverflow.com/questions/273192/check-if-a-directory-exists-and-create-it-if-necessary) – tommy_o Apr 21 '14 at 17:01

2 Answers2

0

This is what you are looking for:

>>> import re
>>> pattern = re.compile(r'\d+')
>>> a = ['banana 1234', 'apple 456', 'orange 789']
>>> for item in a:
...     dir_name = 'D:/python_study/images/skelbimai/{}'.format(re.search(pattern, item).group(0))
...     if not os.path.isdir(dir_name):
...         os.mkdir(dir_name)

This is how it works. The regex finds the numbers in each of the elements of the list. You cah check it by doing:

>>> import re
>>> pattern = re.compile(r'\d+')
>>> a = ['banana 1234', 'apple 456', 'orange 789']
>>> for item in a:
...     print re.search(pattern, item).group(0)
...
'1234'
'456'
'789'

You just concatenate your base directory with each of the numbers calculated as above and call os.mkdir on each. Since you are creating directory in the loop, you do not need makedirs

shaktimaan
  • 11,962
  • 2
  • 29
  • 33
  • ok. VERY COOL. But if numbers are repeat and I get and error that folder is already created. How to evade that? :/ You see the numbers in list seem to repeat. – K00764 Apr 21 '14 at 17:05
  • I get an error "AttributeError: 'NoneType' object has no attribute 'group'" – K00764 Apr 21 '14 at 17:17
  • @user3383245 I made a change in `dir_name`. It shows no error for me. Are my list `a` and your list the same? – shaktimaan Apr 21 '14 at 17:23
  • That was probably because file contained few "\n". But when I used other file without "\n". It created only two folders instead of 19. And throws no error. – K00764 Apr 21 '14 at 17:36
0

Try this

for length in atrinkta:
    folder = re.search(r'(\d+)', length)
    os.makedirs("D:/python_study/images/skelbimai/" + folder.groups()[0])
Rod Xavier
  • 3,983
  • 1
  • 29
  • 41