2

i am trying to create bulk folders based on simple text file. os.makedir helps to create new folder but i am not sure how to incorporate with newpath variable along with folder list. following is what i am trying with. I understand that code has syntax error. So need some help to correct/enhance the code.

import os.path  
newpath = r'C:\Program Files\test\'  
with open('folders.txt') as f:  
    for line in f:  
        ff = os.makedirs(newpath,line.strip())  
        ff.close()
Rostyslav Dzinko
  • 39,424
  • 5
  • 49
  • 62
user1582596
  • 503
  • 2
  • 5
  • 16

3 Answers3

3

Use os.path.join to join path components.

import os.path  
newpath = r'C:\Program Files\test\'  
with open('folders.txt') as f:  
    for line in f:  
        os.makedirs(os.path.join(newpath, line.strip()))
snakile
  • 52,936
  • 62
  • 169
  • 241
2

You can use os.path.join function documented here.

apatrushev
  • 346
  • 3
  • 5
1

Perhaps something like this?

import os, sys
newpath = 'C:\Program Files\test'
with open(open('folders.txt') as f:
  for line in f:
    newdir = os.path.join(newpath, line.strip())
    try:
      os.makedirs(newdir)
    except OSError:  # if makedirs() failed
      sys.stderr.write("ERR: Could not create %s\n" % newdir)
      pass  # continue with next line

Notes:

  • Use os.path.join() to combine a paths. This will automatically use separators that are suitable for your OS.
  • os.makedirs() does not return anything
  • os.makedirs() will raise an OSError exception if the directory already exists or cannot be created.
Shawn Chin
  • 84,080
  • 19
  • 162
  • 191
  • if i am not using '\\' i am getting SyntaxError ' EOL while scanning string literal' wondering if there is any tweak so i can use path with '\'. – user1582596 Aug 29 '12 at 11:04
  • 1
    See this question: http://stackoverflow.com/questions/2870730/python-raw-strings-and-trailing-backslash. For a quick solution, just skip the last slash (`r'C:\Program Files\test'`). `os.path.join()` will still do the right thing. Answer updated. – Shawn Chin Aug 29 '12 at 11:09