How to create new folder?
Solution 1
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.
Solution 2
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.
Solution 3
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)
Related videos on Youtube
![Double AA](https://i.stack.imgur.com/BDSa0.png?s=256&g=1)
Double AA
Updated on September 26, 2020Comments
-
Double AA almost 4 years
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"
andalex
folder doesn't exist then program should createalex
folder and should put output information in thealex
folder.-
user1066101 almost 15 yearsWhen you looked in the
os
module, what did you find? Anything useful? What code did you try? Anything?
-
-
Wayne Koorts almost 15 yearsThis will fail because you haven't double-backslashes in the call to os.makedirs.
-
hughdbrown almost 15 yearsIt's killing me: newpath = r'C:\Program Files\alex'; if not os.path.exists(newpath): os.makedirs(newpath)
-
SilentGhost almost 15 yearsgenerally speaking pathnames are case-sensitive.
-
QxQ about 11 yearsdo
os.path.join('dir','other-dir')
instead ofdir\other-dir
if you want to be compatible with stuff besides windows. -
Ando Jurai about 7 yearsCould someone explain why os.path.join('dir','other-dir') would be more compatible with other systems? Because of slashes/backslashes?
-
Alan Leuthard about 7 yearsBecause 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.
-
mLstudent33 about 5 years
whatever
is a path? -
Thomas meriaux almost 4 years@mLstudent33 Yes as string. I would suggest at least logging the error or a print statement so we know there is something wrong.
-
Amin Pial about 3 yearsthis will fail because you don't have Administrator privilege to create a folder in Programs C Directory.