Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
@mutellipiqbal

This comment has been minimized.

Copy link

@mutellipiqbal mutellipiqbal commented Oct 16, 2017

very useful.

@nickgeorgeseo

This comment has been minimized.

Copy link

@nickgeorgeseo nickgeorgeseo commented Nov 14, 2017

Awesome!!! Thank you.

@Leieland

This comment has been minimized.

Copy link

@Leieland Leieland commented Nov 27, 2017

Thks...

@ganeshhubale

This comment has been minimized.

Copy link

@ganeshhubale ganeshhubale commented Feb 28, 2018

Thank you so much

@rec16005

This comment has been minimized.

Copy link

@rec16005 rec16005 commented Apr 20, 2018

Thank you!
If someone is getting a unicode error when trying to create a folder in a directory (C\Users\etc...) just duplicate all backslashes like this (C\Users\etc...)

@stefan-wullems

This comment has been minimized.

Copy link

@stefan-wullems stefan-wullems commented Jun 6, 2018

Saved me from writing 600+ new directories.

@j5207

This comment has been minimized.

Copy link

@j5207 j5207 commented Jul 11, 2018

Thanks

@hjoon0510

This comment has been minimized.

Copy link

@hjoon0510 hjoon0510 commented Jul 24, 2018

good!

@hjoon0510

This comment has been minimized.

Copy link

@hjoon0510 hjoon0510 commented Jul 24, 2018

I wonder how decide directory name?

@gwangjinkim

This comment has been minimized.

Copy link

@gwangjinkim gwangjinkim commented Aug 23, 2018

Isn't this all already done by

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

? (thanks @EricHedengren for correction below! ;)

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

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

@EmoryMullis

This comment has been minimized.

Copy link

@EmoryMullis EmoryMullis commented Sep 16, 2018

hjoon0510 I am working on learning Python myself but as to selecting the NAME. I import the "socket", then set a variable to hostname = socket.gethostname(). I can then call that variable to name my file or directory. Again I am trying to learn also so there may be a better way to do it but here is the code I am playing with to learn.
import wmi
import datetime
import sys
import os
import platform
import getpass
import socket
import ifaddr
from psutil import virtual_memory

ps = platform.system()
pr = platform.release()
build = platform.version()
cdir = os.getcwd()
mem = virtual_memory()
username = getpass.getuser()
hostname = socket.gethostname()
adapters = ifaddr.get_adapters()
mType = platform.machine()
pType = platform.processor()
currentDT = datetime.datetime.now()

def createFolder(directory):
try:
if not os.path.exists(hostname):
os.makedirs(hostname)
except OSError:
return ('Error: Creating directory. ' + hostname)

createFolder('./hostname/')

sys.stdout = open("%s %s" % (hostname, (currentDT.strftime("%m%d%Y %H%M%S"))) + ".txt", "w+")

HDs = wmi.WMI()
for hdSerialnum in HDs.Win32_PhysicalMedia():
print(hdSerialnum.Tag.strip("\.\PHYSICAL"), hdSerialnum.SerialNumber)
print('')

print("Installed OS: " + ps + '\n' + "OS Version: " + pr + '\n' + "OS Build: " + build + '\n' +
"Current Dir: " + cdir + '\n' + "Machine Type: " + mType + '\n' + "Processor: " +
pType + '\n' + "RAM Total: " + str(mem.total) + '\n' + "Current User Name: "
+ username + '\n' + "Computer Name: " + hostname + '\n')

for adapter in adapters:
print(adapter.nice_name)
for ip in adapter.ips:
print(" %s/%s" % (ip.ip, ip.network_prefix))

sys.stdout.close()

@niceinjeolmi

This comment has been minimized.

Copy link

@niceinjeolmi niceinjeolmi commented Feb 1, 2019

thank you so much!

@mosestkamau

This comment has been minimized.

Copy link

@mosestkamau mosestkamau commented May 18, 2019

This is wonderful!

@rohit1607

This comment has been minimized.

Copy link

@rohit1607 rohit1607 commented Jul 10, 2019

Thanks alot!

@DongaEG

This comment has been minimized.

Copy link

@DongaEG DongaEG commented Sep 1, 2019

thank u

@Matin-B

This comment has been minimized.

Copy link

@Matin-B Matin-B commented Sep 20, 2019

Thanks

@GwenVCX

This comment has been minimized.

Copy link

@GwenVCX GwenVCX commented Sep 30, 2019

Thank you! :)

@chichur

This comment has been minimized.

Copy link

@chichur chichur commented Oct 25, 2019

Thank BRO!!!

@sankarsarika74

This comment has been minimized.

Copy link

@sankarsarika74 sankarsarika74 commented Nov 28, 2019

you can change your directory by os.chdir

@Moonshine42tech

This comment has been minimized.

Copy link

@Moonshine42tech Moonshine42tech commented Jan 30, 2020

Thank you

@DATTUSAM

This comment has been minimized.

Copy link

@DATTUSAM DATTUSAM commented May 16, 2020

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

This comment has been minimized.

Copy link

@eric-hedengren 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

This comment has been minimized.

Copy link

@gwangjinkim gwangjinkim commented Jul 9, 2020

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

@khu17jain

This comment has been minimized.

Copy link

@khu17jain khu17jain commented Jul 17, 2020

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

@eric-hedengren

This comment has been minimized.

Copy link

@eric-hedengren eric-hedengren commented Jul 19, 2020

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

@qdb99581

This comment has been minimized.

Copy link

@qdb99581 qdb99581 commented Jan 26, 2021

best code I have ever found, thx!

@JeremyMeissner

This comment has been minimized.

Copy link

@JeremyMeissner JeremyMeissner commented Mar 3, 2021

Thank you!

@Hemantphareesh

This comment has been minimized.

Copy link

@Hemantphareesh Hemantphareesh commented Jun 9, 2021

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

@danialmEssi

This comment has been minimized.

Copy link

@danialmEssi danialmEssi commented Sep 19, 2021

thank you man ``

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