219

I want to put output information of my program to a folder. if given folder does not exist, then the program should create a new folder with folder name as given in the program. Is this possible? If yes, please let me know 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.

Double AA
  • 5,019
  • 15
  • 40
  • 53
  • 9
    When you looked in the `os` module, what did you find? Anything useful? What code did you try? Anything? – S.Lott Aug 13 '09 at 20:35

3 Answers3

347

You can create a folder with os.makedirs()
and use os.path.exists() to see if it already exists:

newpath = r'C:\Program Files\arbitrary' 
if not os.path.exists(newpath):
    os.makedirs(newpath)

If you're trying to make an installer: Windows Installer does a lot of work for you.

Pixdigit
  • 80
  • 2
  • 11
mcandre
  • 19,306
  • 17
  • 77
  • 140
  • 9
    This will fail because you haven't double-backslashes in the call to os.makedirs. – Wayne Koorts Aug 13 '09 at 21:11
  • 2
    It's killing me: newpath = r'C:\Program Files\alex'; if not os.path.exists(newpath): os.makedirs(newpath) – hughdbrown Aug 14 '09 at 02:20
  • generally speaking pathnames are case-sensitive. – SilentGhost Aug 17 '09 at 14:09
  • 31
    do `os.path.join('dir','other-dir')` instead of `dir\other-dir` if you want to be compatible with stuff besides windows. – QxQ Apr 15 '13 at 20:56
  • 1
    Could someone explain why os.path.join('dir','other-dir') would be more compatible with other systems? Because of slashes/backslashes? – Ando Jurai May 04 '17 at 07:37
  • 5
    Because os.path functions use the local rules of the python installation running the script for path strings. Using os.path.join in all cases assures that your paths will be formed correctly for the platform the script is being run on. – Alan Leuthard Jun 13 '17 at 21:12
43

Have you tried os.mkdir?

You might also try this little code snippet:

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

makedirs creates multiple levels of directories, if needed.

Nick Volynkin
  • 11,882
  • 6
  • 39
  • 62
Juergen
  • 11,315
  • 7
  • 34
  • 53
38

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

import os

#dir is not keyword
def 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)
trean
  • 35
  • 9
Alex Martelli
  • 762,786
  • 156
  • 1,160
  • 1,345