Skip to content

Python, how to create a directory

New Course Coming Soon:

Get Really Good at Git

To create a directory, use the os.mkdir() method provided by the os standard library module:

import os

dirname = '/Users/flavio/test'

os.mkdir(dirname)

Creating a folder can raise an OSError exception, for example if the disk is full or the directory already exists, so we use a try block to catch it and gracefully handle the problem by printing an error message:

import os

dirname = '/Users/flavio/test'

try:
    os.mkdir(dirname)
except OSError:
    print('Failed creating the directory')
else:
    print('Directory created')
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my Python Handbook
→ Get my Python Handbook

Here is how can I help you: