Python check folder exists and create

Create directory if it does not exist in Python

As a Python developer, I’ve often found myself in situations where I need to create directories dynamically within my code. However, there’s always the concern that the directory might already exist, leading to errors or unwanted behavior. That’s where the beauty of Python shines through. In this blog post, I’ll walk you through the process of creating a directory if it does not exist in Python. With this knowledge, you’ll be able to handle directory creation seamlessly and ensure smooth execution of your code.

Читайте также:  Html hide iframe borders

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.,

Method 1: Using os.path.exists and create the directory if it doesn’t exist

Step 1: Check if the folder exists using os.path.exists

Let’s achieve this in 2 steps, firstly we will use the os.path.exists() method to see if a directory already exists, and then let’s use the os.makedirs() method to create the directory.

You can check if a directory already exists in the path by checking the following os.path.exists(path) .

In the code below we will check if the directory path exists. os.path.exists returns a boolean value which is then printed.

import os path = "path-to-directory" isExist = os.path.exists(path) print(isExist) 

Since the path to the directory didn’t exist it returned False . In case the directory exists, it’ll return True .

Step 2: Create directory conditionally if it doesn’t exist

Here we will extend the above code, the isExist variable will help us to determine if we have to create a directory conditionally.

import os path = "path-to-directory" isExist = os.path.exists(path) if not isExist:  os.makedirs(path)  print('Successfully created directory') 
Successfully created directory 

The os.makedirs() creates the directory recursively. In case you are specifically looking to create recursive directories in python check the article, where we cover various examples on this topic.

Method 2: Using os.path.isdir and create the directory if it doesn’t exist

Step 1 : Check if the path is a directory using os.path.isdir

Let’s achieve this in 2 steps, firstly we will use the os.path.isdir() method to see if the path is a directory, and then let’s use the os.makedirs() method to create the directory.

In the code below we will check if the path path is a directory. os.path.isdir returns a boolean value which is then printed.

import os path = "path-to-directory" isDir = os.path.isdir(path) print(isDir) 

Since the path to the directory didn’t exist it returned False . In case the directory exists, it’ll return True .

Step 2 : Create directory conditionally if it doesn’t exist or is not a directory

Here we will extend the above code, the isDir variable will help us to determine if we have to create a directory conditionally.

import os path = "path-to-directory" isDir = os.path.isdir(path) if not isDir:  os.makedirs(path)  print('Successfully created directory') 
Successfully created directory 

As you see in the above code examples, it’s pretty simple to create folders if it doesn’t already exist in Python.

And there you have it! We’ve reached the end of our journey on how to create a directory if it does not exist in Python. It’s a simple yet powerful technique that can save you from potential headaches and errors. By employing the techniques we’ve covered, you can confidently create directories on the fly and organize your data effortlessly. Python continues to amaze with its flexibility and ease of use, empowering developers like us to achieve great things. Happy coding and may your directories always exist exactly where you need them!

Источник

How can I create a directory if it does not exist using Python?

Python has built in file creation, writing, and reading capabilities. In Python, there are two sorts of files that can be handled: text files and binary files (written in binary language, 0s, and 1s). While you can create files you may delete them when you no longer need them.

It is simple to create directories programmatically, but you must ensure that they do not already exist. You’ll have difficulties if you don’t.

Example 1

In Python, use the os.path.exists() method to see if a directory already exists, and then use the os.makedirs() method to create it.

The built in Python method os.path.exists() is used to determine whether or not the supplied path exists. The os.path.exists() method produces a boolean value that is either True or False depending on whether or not the route exists.

Python’s OS module includes functions for creating and removing directories (folders), retrieving their contents, altering and identifying the current directory, and more. To interface with the underlying operating system, you must first import the os module.

#python program to check if a directory exists import os path = "directory" # Check whether the specified path exists or not isExist = os.path.exists(path) #printing if the path exists or not print(isExist)

Output

On executing the above program, the following output is generated.

True Let’s look at a scenario where the directory doesn’t exist.

Example 2

The built in Python method os.makedirs() is used to recursively build a directory.

#python program to check if a directory exists import os path = "pythonprog" # Check whether the specified path exists or not isExist = os.path.exists(path) if not isExist: # Create a new directory because it does not exist os.makedirs(path) print("The new directory is created!")

Output

On executing the above program, the following output is generated.

The new directory is created!

Example 3

To create a directory, first check if it already exists using os.path.exists(directory). Then you can create it using −

#python program to check if a path exists #if it doesn’t exist we create one import os if not os.path.exists('my_folder'): os.makedirs('my_folder')

Example 4

The pathlib module contains classes that represent filesystem paths and provide semantics for various operating systems. Pure paths, which give purely computational operations without I/O, and concrete paths, which inherit from pure pathways but additionally provide I/O operations, are the two types of path classes.

# python program to check if a path exists #if path doesn’t exist we create a new path from pathlib import Path #creating a new directory called pythondirectory Path("/my/pythondirectory").mkdir(parents=True, exist_ok=True)

Example 5

# python program to check if a path exists #if path doesn’t exist we create a new path import os try: os.makedirs("pythondirectory") except FileExistsError: # directory already exists pass

Источник

Support Our Site

To ensure we can continue delivering content and maintaining a free platform for all users, we kindly request that you disable your adblocker. Your contribution greatly supports our site’s growth and development.

Python Script To Check If A Directory Exists, If Not, Create It

Check If A Directory Exists, If Not, Create It

The 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.

Program

'''Check if directory exists, if not, create it''' import os # You should change 'test' to your preferred folder. MYDIR = ("test") CHECK_FOLDER = os.path.isdir(MYDIR) # If folder doesn't exist, then create it. if not CHECK_FOLDER: os.makedirs(MYDIR) print("created folder : ", MYDIR) else: print(MYDIR, "folder already exists.") 

Output

Explanation

First, we are importing the OS module next we are declaring the directory which we will look for you should change it to your preferred directory or folder name. Then we are using the os.path.isdir(MYDIR) method and looking for our folder on the system and below that we have a set of conditional operation which creates a new directory with a given name using os.makedirs(MYDIR) method if the isdir() method evaluates to false. Note that the folder or directory will be generated at the location where the script exists.

Источник

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.

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!

Источник

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