Skip to content

Instantly share code, notes, and snippets.

@keithweaver
Created March 10, 2017 03:42
Show Gist options
  • Save keithweaver/562d3caa8650eefe7f84fa074e9ca949 to your computer and use it in GitHub Desktop.
Save keithweaver/562d3caa8650eefe7f84fa074e9ca949 to your computer and use it in GitHub Desktop.
Create a folder with Python
import os
def createFolder(directory):
try:
if not os.path.exists(directory):
os.makedirs(directory)
except OSError:
print ('Error: Creating directory. ' + directory)
# Example
createFolder('./data/')
# Creates a folder in the current directory called data
@chichur
Copy link

chichur commented Oct 25, 2019

Thank BRO!!!

@sankarsarika74
Copy link

you can change your directory by os.chdir

@KasperRagnar
Copy link

Thank you

@DATTUSAM
Copy link

Thank you very much..... keithweaver

if anybody facing issue while creating the folder, followed with an error message like this
def createFolder(D:\Sampath\web_scrapper\temp):
^
SyntaxError: unexpected character after line continuation character

please just duplicate with a backslash for the directory you want to create. Here I want to create a Temp folder in web_scrapper folder
createFolder('D:\Sampath\PAMM_web_scrapper/temp/')

@eric-hedengren
Copy link

eric-hedengren commented Jul 9, 2020

Isn't this all already done by

import os
os.mkdirs(directory, exist_ok = True)

?

exist ok = True checks for existence and makes dir created if not existing

OSErrors from the os package will do the error messaging ...

You're right @gwangjinkim. Just switch mkdirs to makedirs and it's good to go.

import os
os.makedirs(directory, exist_ok = True)

@gwangjinkim
Copy link

@EricHedengren thanks! True! I always have to look this up anew.

@khu17jain
Copy link

if i would like to create two folders in single directory how to do that

@eric-hedengren
Copy link

@khu17jain Write two makedirs statements to the same location. For loop it if you have a lot.

@tzuhungbrian
Copy link

best code I have ever found, thx!

@JeremyMeissner
Copy link

Thank you!

@Hemantphareesh
Copy link

how to create a folder with name in format yyyy-mm-dd from any year to today

@DanialBahrizadeh
Copy link

thank you man ``

@SaberKazemii
Copy link

Great! Thanks so much!

@lucasgcruz
Copy link

Thank you, very useful and helped me understand the command.

@sourcecodemage
Copy link

NIce! Thanks for posting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment