How to create new folder?

Question:

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 Filesalex" and alex folder doesn’t exist then program should create alex folder and should put output information in the alex folder.

Asked By: alex

||

Answers:

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.

Answered By: Juergen

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

newpath = r'C:Program Filesarbitrary' 
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.

Answered By: mcandre

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)
Answered By: Alex Martelli
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.