The Python Oracle

How to create new folder?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Realization

--

Chapters
00:00 Question
00:36 Accepted answer (Score 455)
01:02 Answer 2 (Score 65)
01:24 Answer 3 (Score 42)
01:44 Thank you

--

Full question
https://stackoverflow.com/questions/1274...

Accepted answer links:
[os.makedirs()]: http://docs.python.org/3/library/os.html...
[os.path.exists()]: http://docs.python.org/3/library/os.path...
[Windows Installer]: http://www.advancedinstaller.com/

Answer 3 links:
[os.makedirs]: http://docs.python.org/library/os.html?h...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #mkdir

#avk47



ACCEPTED ANSWER

Score 569


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.




ANSWER 2

Score 76


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.




ANSWER 3

Score 52


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)