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
  • 38,056
  • 5
  • 48
  • 60
user1582596
  • 429
  • 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
  • 50,186
  • 60
  • 164
  • 235
2

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

apatrushev
  • 166
  • 1
  • 4
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
  • 79,172
  • 18
  • 156
  • 188
  • 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