tags:

views:

307

answers:

3

I want to put output information of my program to a folder. if given folder is not exit, then program should create a new folder with folder name as given in the program. is it possible? if yes please let me how. suppose i have given folder path like "C:\Program Files\alex" and alex folder doesn't exist then program should create alex folder and should put output information in the alex folder.

+6  A: 

Have you tried os.mkdir?

You might also try this little code snipped:

mypath = ...
if not os.path.isdir(mypath):
   os.makedirs(mypath)

makedirs does create multiple levels of directories, if needed.

Juergen
+1  A: 
newpath = r'C:\Program Files\alex'; if not os.path.exists(newpath): os.makedirs(newpath)

From Python docs.

It looks like you're trying to make an installer. Windows Installer does a lot of work for you.

mcandre
This will fail because you haven't double-backslashes in the call to os.makedirs.
Wayne Koorts
It's killing me: newpath = r'C:\Program Files\alex';if not os.path.exists(newpath): os.makedirs(newpath)
hughdbrown
generally speaking pathnames are case-sensitive.
SilentGhost
Thanks hughdbrown.
mcandre
+2  A: 

You probably want os.makedirs as it will create intermediate directories as well, if needed.

import os

dir makemydir(whatever):
  try:
    os.makedirs(whatever)
  except OSError:
    pass
  # let exception propagate if we just can't
  # cd into the specified directory
  os.chdir(whatever)
Alex Martelli