Create directories using python

Creating a Directory in Python – How to Create a Folder

Dionysia Lemonaki

Dionysia Lemonaki

Creating a Directory in Python – How to Create a Folder

In this article, you will learn how to create new directories (which is another name for folders) in Python.

You will also learn how to create a nested directory structure.

To work with directories in Python, you first need to include the os module in your project, which allows you to interact with your operating system.

The os module also lets you use the two methods we will cover in this article:

How To Create A Single Directory Using The os.mkdir() Method in Python

As mentioned earlier, to work with directories in Python, you first need to include the os module.

To do so, add the following line of code to the top of your file:

The code above will allow you to use the os.mkdir() method to create a new single directory.

The os.mkdir() method accepts one argument – the path for the directory.

import os # specify the path for the directory – make sure to surround it with quotation marks path = './projects' # create new single directory os.mkdir(path) 

The code above will create a projects directory in the current working directory.

Note that the ./ stands for the current working directory. You can omit this part and only write projects when specifying the path – the result will be the same!

How to Handle Exceptions When Using the os.mkdir Method in Python

But what happens when the directory you are trying to create already exists? A FileExistsError exception is raised:

Traceback (most recent call last): File "main.py", line 3, in os.mkdir(path) FileExistsError: [Errno 17] File exists: './projects' 

One way to handle this exception is to check if the file already exists using an if..else block:

import os path = './projects' # check whether directory already exists if not os.path.exists(path): os.mkdir(path) print("Folder %s created!" % path) else: print("Folder %s already exists" % path) 

In the example above, I first checked whether the ./projects directory already exists using the os.path.exists() method.

Читайте также:  Php manager для html

If it does, I will get the following output instead of a FileExistsError :

Folder ./projects already exists 

If the file doesn’t exist, then a new projects folder gets created in the current working directory, and I get the following output:

Alternatively, you can use a try/except block to handle exceptions:

import os path = './projects' try: os.mkdir(path) print("Folder %s created!" % path) except FileExistsError: print("Folder %s already exists" % path) 

If a projects folder already exists in the current working directory, you will get the following output instead of an error message:

Folder ./projects already exists 

How To Create A Directory With Subdirectories Using The os.makedirs() Method in Python

The os.mkdir() method does not let you create a subdirectory. Instead, it lets you create a single directory.

To create a nested directory structure (such as a directory inside another directory), use the os.makedirs() method.

The os.makedirs() accepts one argument – the entire folder path you want to create.

import os # define the name of the directory with its subdirectories path = './projects/games/game01' os.makedirs(path) 

In the example above, I created a projects directory in the current working directory.

Inside projects, I created another directory, games . And inside games , I created yet another directory, games01 .

Conclusion

And there you have it! You now know how to create a single directory and a directory with subdirectories in Python.

To learn more about Python, check out freeCodeCamp’s Python for beginners course.

Thanks for reading, and happy coding!

Источник

Create Directory in Python

Python Certification Course: Master the essentials

Python has an OS module in its standard utility modules that provides several functionalities to interact with the underlying operating systems and the files. If an inaccessible or invalid path, file name, or other arguments are passed to methods in OS module, OSError is raised by the program. OS module provides two methods os.mkdir() and os.makedirs() that are used to create directories using Python in the file system.

Introduction

introduction to Python create directory

Python has an OS module that provides several functionalities to interact with the underlying operating systems and the files. OS module comes under Python’s standard utility modules, and you do not need to install or download this module separately from your Python installation. But it is not a built-in module so we have to import it before use. OS module provides the programmer with a portable way of accessing and using operating system dependent functionality. Several functions to interact with the computer’s file system is provided in the os and os.path modules. If an inaccessible or invalid path, file name, or other arguments are passed to methods in OS module, OSError is raised by the program even if they have correct types but are not accepted by the underlying operating system as a valid argument.

Читайте также:  Fun maps on css

OS module provides two different methods for creating directories in Python, that are —

Let us understand both of these two methods in detail.

Method 1: Using os.mkdir() Method to Create a Directory in Python

OS module has an in-built method os mkdir() to create directories using Python in the system.

Syntax

Two arguments are passed to the method they are

  • path: A path is a string or byte value that includes the complete path and the name of the directory to be created. path argument is basically the location where the user wants to create a directory.
  • mode(optional): This is an optional argument that the user may pass. It contains the information about the permissions that need to be given to deal with the file operations within the directory. The default value is 0o777 (octal).

Example 1: Create a Directory using Python in a specified location

Create a Directory using Python in a specified location

In the above example, we are passing the path string that has the location followed by name of the new directory that we need to create. The function doesn’t have any return type and the code will continue without any error if the new directory is successfully created, otherwise program will throws an OSError .

Example 2: Providing Permissions for Reading and Writing Operations Within the Directory

Providing permissions for reading and writing operations within the directory

Here, setting mode = 0o666 allows the user to perform read and write file operations within the created directory.

Exceptions with os.mkdir() Method

The os.mkdir() method in OS module raises a FileExistsError if the directory in the location specified as path already exists. For example, after executing example 1, the directory will be created, and if we try to execute the same program again following error will be raised.

Method 2: Using os.makedirs()

Another way to create a directory in Python is using the os.makedirs() method built-in in the OS module to create nested directories within the system. The os.makedirs() function creates a parent directory, intermediate directories, and leaf directories (leaf directories are those directories that occur at the end of a path) if they are not already present in the file system.

Читайте также:  Php fpm windows service

The syntax of it is similar to os.mkdir() and two arguments of os.makedirs() is same as os.mkdir() function i.e., path and mode. Apart from these two arguments os.makedirs() also has a third optional argument that is

  • exist_ok(optional): A default value of optional is False . If the target directory already exists in the file system, an OSError is raised if the value of this parameter is False ; otherwise, no error will be raised by the function.

Using osmakedirs

Here, the makedirs() function creates the OS_Module directory (leaf directory) as well as creates an intermediate directory, i.e. Lib.

Exceptions with os.makedirs() Method

Just like os.mkdir() method, os.mkdir() method also raises the same FileExistsError if the directory in the location specified as path already exists. This can be understood when we try to create the same directories that we created in the previous example.

Handling Errors While Using os.mkdir() or os.makedirs() Methods

Handling errors while using osmakedirs methods

We know that if an inaccessible or invalid path, file name, or other arguments are passed to functions in OS module, OSError is raised by the program even if they have correct types but are not accepted by the underlying operating system. We can put the os functions inside the try block to prevent programs from abruptly terminating when OSErrors are raised by functions in OS module. Let us see this with examples.

Example 1: Handling Error While Using os.mkdir() Method

Example 2: Handling Error While Using os.makedirs() Method

Conclusion

  • OS module comes under Python’s standard utility modules that provide several functionalities to interact with the underlying operating systems and the files.
  • If an inaccessible or invalid path, file name, or other arguments are passed to methods in OS module, OSError is raised by the program even if they have correct types but are not accepted by the underlying operating system.
  • OS module provides two different methods for creating directories using Python, that are os.mkdir() , os.makedirs() .
  • Both the methods have common two arguments that are path and an optional argument mode, but os.makedirs() also has an optional third argument which is exist_ok .
  • Path is a string or byte value which includes the complete path and the name of the directory to be created, and mode contains the information about the permissions that need to be given to deal with the file operations within the directory. The default value is 0o777 .

Источник

Оцените статью