From the course: Python: Working with Files

Unlock the full course today

Join today to access over 24,900 courses taught by industry experts.

Create directories in Python

Create directories in Python - Python Tutorial

From the course: Python: Working with Files

Create directories in Python

- [Instructor] When working with files, sometimes you'll want to create a directory path to store log files or output files. Let's look at a few different ways we can create folders or directories in Python. One way is with the os module. We can use os.mkdir to create a new directory. We can name it by passing in the name of the directory as a parameter. We'll call it logs. This will create a directory wherever this Python program is run since this path is a relative path. We also have the option of using an absolute path here as well. If this directory already happens to exist, then make directory will raise a file exists error. To handle this, we can wrap our mkdir call in a try block. If the directory already exists, we'll print out a message instead of letting the error be raised. Let's execute this program and watch it create the logs directory. Looking at our desktop, there's our logs directory. We haven't…

Contents