Python mkdir and check

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

Источник

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!

Источник

Create Directory in Python

Create Directory in Python

  1. Create Directory in Python Using the path.exists() and makedirs() Methods of the os Module
  2. Create Directory in Python Using the Path.mkdir() Method of the pathlib Module

This tutorial will explain various methods to check if a directory exists and how to create the directory if it does not exist. Suppose we want to save a file in a specific path like C:\myfolder\myfile.txt , if the myfolder exists, the myfile.txt should be saved there, and if not, we want first to create the myfolder directory and then save the file in it. We can use the following methods in Python to achieve this goal.

Create Directory in Python Using the path.exists() and makedirs() Methods of the os Module

The path.exists() method checks if the given path exists and returns True if it exists and False otherwise. The makedirs() takes the path as input and creates the missing intermediate directories in the path.

The code example below demonstrates how to check the existence of the directory and create it if it does not exist in Python:

import os  if not os.path.exists('parentdirectory/mydirectory'):  os.makedirs('parentdirectory/mydirectory') 

We can also use the try . except statement with the makedirs() method to check the existence and otherwise create the directory.

try:  os.makedirs('parentdirectory/mydirectory') except FileExistsError:  pass 

Create Directory in Python Using the Path.mkdir() Method of the pathlib Module

The Path.mkdir() method, in Python 3.5 and above, takes the path as input and creates any missing directories of the path, including the parent directory if the parents flag is True . The Path.mkdir will return the FileNotFoundError if the parent directory is missing if the parents flag is False , but will still create the intermediate directories. exist_OK is False by default, meaning it raises FileExistsError if the given directory already exists. When exist_OK is True , it will ignore FileExistsError .

To check if the directory exists and create it if it does not exist, we need to pass the directory path to the Path.mkdir() method while setting the required flags True . The example code below demonstrates how to use the Path.mkdir() for this task.

from pathlib import Path  path = Path("parentdirectory/mydirectory") path.mkdir(parents=True, exist_ok=True) 

Related Article — Python Directory

Источник

Читайте также:  Php http request password
Оцените статью