Python make directory recursive

Python | os.makedirs() method

OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by the operating system.
os.makedirs() method in Python is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing, os.makedirs() method will create them all.
For example consider the following path:

/home/User/Documents/GeeksForGeeks/Authors/ihritik

Suppose we want to create directory ‘ihritik’ but Directory ‘GeeksForGeeks’ and ‘Authors’ are unavailable in the path. Then os.makedirs() method will create all unavailable/missing directory in the specified path. ‘GeeksForGeeks’ and ‘Authors’ will be created first then ‘ihritik’ directory will be created.

Syntax: os.makedirs(path, mode = 0o777, exist_ok = False)
Parameter:
path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.
mode (optional) : A Integer value representing mode of the newly created directory..If this parameter is omitted then the default value Oo777 is used.
exist_ok (optional) : A default value False is used for this parameter. If the target directory already exists an OSError is raised if its value is False otherwise not. For value True leaves directory unaltered.
Return Type: This method does not return any value.

Code #1: Use of os.makedirs() method to create directory

Источник

How to create a directory recursively using Python?

In Python programming, operations on files and directories are routine tasks that you carry out daily and are a common requirement. Having a rich set of libraries and intuitive syntax, Python provides a simple and straightforward way to carry out such tasks. Here, in this article, we will explore and learn how to create directories recursively using Python. It does not matter if you are either a beginner or an experienced developer, this article will guide you in a step-by-step manner to help you acquire this essential skill. So, let’s start acquiring the knowledge of creating directories effortlessly using Python!

Understanding Directory Structure

Before we start creating directories, let us first attempt to understand the concept of directory structure. A directory is a folder that further contains more files and subdirectories. Directories are organized hierarchically, resembling a tree-like structure. The task of creating directories recursively means creating not only the target directory but also creating any missing parent directories leading up to it.

The os Module in Python

To interact and work with the operating system and carry out file and directory operations in Python, we use the os module. This module provisions for a wide range of functions and methods to manipulate directories, files, and paths.

Читайте также:  Php soap error parsing wsdl failed to load external entity

Checking if a Directory Exists

Before we create a directory, it’s a good idea to check if it already exists. The os.path.exists() function is used for this purpose. Here’s an example:

Example

import os directory = '/path/to/directory' if not os.path.exists(directory): print("Directory does not exist") else: print("Directory already exists")

Output

For one particular directory, the output can be

In the above given code, we verify and check if the directory at any given path exists or unit making use of the os.path.exists() function.

Creating a Directory

To make a directory or folder in Python, we also use the os.mkdir() function. However, this function creates a single directory at a time. To make directories recursively, we should use the os.makedirs() function. Here is how it done in the example given below:

import os directory = '/path/to/new/directory' os.makedirs(directory)

The os.makedirs() function makes the directory at the given path, including any missing parent directories.

Handling Exceptions

When directories are created, it’s important to handle exceptions and errors that may happen. For example, if the parent directory is read-only or if the user has insufficient permissions, an exception will be raised. In such a scenario, we can use the try-except block to handle such exceptions effectively. Let us consider an example below:

Example

import os directory = '/path/to/new/directory' try: os.makedirs(directory) print("Directory created successfully") except OSError as e: print(f"Error: ")

Output

For one particular new directory, the output can be

Error: [Errno 13] Permission denied: '/path'

In the above code, we make an attempt to create the directory, and if an exception happens, we try to catch it and display an error message.

Putting It All Together

By now we have explored the basics; let us put our acquired knowledge into use by creating a complete Python script to create directories recursively:

Here, in the code below, we declare a function create_directory() that takes a directory path as an argument and makes an attempt to create the directory using os.makedirs(). We handle any exceptions or errors that may occur and provide befitting feedback to the user.

Example

import os def create_directory(directory): try: os.makedirs(directory) print(f"Directory '' created successfully") except OSError as e: print(f"Error: ") # Example usage create_directory('/path/to/new/directory')

Output

For one particular new directory, the output can be

Directory '/content/paloma' created successfully

It is obvious that by now you have now learned how to create directories recursively using Python. We have explored the os module and its functions for directory creation operations.

Making Use of Pathlib Module

The pathlib module in Python, on the other hand, provides an object-oriented approach to handle file system paths. Let us see how you can create directories recursively using pathlib functions and methods:

In this code example, we create a Path object pointing to the target directory. The mkdir() method is called on the directory object with the parents=True argument, and this enables the creation of parent directories if they don’t happen to exist. The exist_ok=True argument makes sure that an exception is not raised if the directory already exists.

from pathlib import Path directory = Path('/path/to/new/directory') directory.mkdir(parents=True, exist_ok=True)

Make Use of os.makedirs() with Multiple Directories

In some instances, you might want to create several directories all at once. You can obtain this by passing a list of directory paths to the os.makedirs() function. Let us consider an example:

Читайте также:  Image to bin python

In the code below, we specify a list of directory paths and make use of a ‘for loop’ to iterate over each directory. The os.makedirs() function is called for each directory, and the exist_ok=True argument ensures that an exception is not raised if any of the directories already exist.

import os directories = ['/path/to/new/directory1', '/path/to/new/directory2', '/path/to/new/directory3'] for directory in directories: os.makedirs(directory, exist_ok=True)

By incorporating the practice of these code examples into your skill set, you now have a broad understanding of how to create directories recursively using Python. You can either choose the os module or the pathlib module; it is up to you to do so. In any case, you have the flexibility to choose the approach that best fits your coding style and requirements.

It is better to handle exceptions properly to make sure smooth execution of code and further explore other functionalities provisioned by the os and pathlib modules to enhance your directory manipulation capabilities or skills.

Источник

Create directory recursively in Python

As a Python developer, I often come across situations where I need to create directories in a recursive manner. Whether it’s organizing files or setting up a directory structure, the ability to create directories programmatically can save a lot of time and effort. In this blog post, I’m thrilled to share with you how to create directories recursively in Python. We’ll explore different techniques and approaches to accomplish this task efficiently. So, let’s dive in and empower ourselves with the knowledge to streamline directory creation in Python!

The os module provides functions for interacting with the Operating System in Python. The os module is standard python utility module. Most Operating System based functionalities are abstracted out in this module and it is provided in a very portable way.

Note — In case of any error or exception, all the functions in the os module raise an OSError . Examples are — trying to create an invalid file name(or folder name), incorrect arguments to the functions, etc.,

Create a single directory in Python using os.mkdir() method

You can create a single directory in python using the os.mkdir() method.

os.mkdir(path, mode = 0o777, *, dir_fd = None) 

The path is the name of the folder either referring to the absolute or relate path depending on how you want it to work.

import os # new folder/dir name new_directory = "debugpointer"  # Parent Directory path # In case of Windows, "D:/" parent_directory = "/home/ubuntu/"  # Setting the path for folder creation path = os.path.join(parent_directory, new_directory)  mode = 0o777  # Create the directory in the path os.mkdir(path, mode) print("Directory %s Created Successfully" % new_directory) 
Directory debugpointer Created Successfully 

Note — FileExistsError is raised when the file already exists in the path. It is advised to handle this error in cases where folder are created often(maybe in a python script that runs every time or the API which creates a folder for some reason, etc.,)

Читайте также:  Уникальные символы в питоне

Create directories recursively using in Python using os.makedirs() method

The os.makedirs() method creates a directory recursively in a given path in Python. This means, you can create folders with-in folders (with-in folder and so on. ) easily using the os.makedirs() method.

os.makedirs(path, mode = 0o777, *, dir_fd = None) 

Suppose you want to create 3 folders one within another in the form — debugpointer => python => posts, you can easily achieve this using the os.makedirs() method. Python makes care of creating the recursive folders for you when you just specify the structure of your folders that you need.

import os # new folder/dir name new_directory = "debugpointer/python/posts"  # Parent Directory path # In case of Windows, "D:/" parent_directory = "/home/ubuntu/"  # Setting the path for folder creation path = os.path.join(parent_directory, new_directory)  mode = 0o777  # Create the directory in the path os.makedirs(path, mode) print("Directory %s Created Successfully" % new_directory) 
Directory debugpointer/python/posts Created Successfully 

Note — FileExistsError is raised when the file already exists in the path. It is advised to handle this error in cases where folder are created often(maybe in a python script that runs every time or the API which creates a folder for some reason, etc.,)

In such cases, you can handle other OSError errors as follows and also use exist_ok = True so that the FileExistsError does not appear and it gets suppressed —

import os # new folder/dir name new_directory = "debugpointer/python/posts"  # Parent Directory path # In case of Windows, "D:/" parent_directory = "/home/ubuntu/"  # Setting the path for folder creation path = os.path.join(parent_directory, new_directory)  # Handle the errors try:  # Create the directory in the path  os.makedirs(path, exist_ok = True)  print("Directory %s Created Successfully" % new_directory) except OSError as error:  print("Directory %s Creation Failed" % new_directory) 
Directory debugpointer/python/posts Created Successfully 

The other option is to check if a directory already exists or not, that would also help in validating existence of the directory path before creating the directory.

As you see in the above code examples, it’s pretty simple to create folders recursively in Python.

And there you have it, a comprehensive understanding of creating directories recursively in Python. We’ve explored various methods and techniques to achieve this task, providing you with the flexibility to adapt to different scenarios. The ability to programmatically create directories in a recursive manner is a valuable skill that can simplify file organization and directory management in your Python projects. I hope this knowledge empowers you to become a more efficient and productive Python developer. Happy coding and creating directories recursively!

Источник

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