Python create directory path

How to create a Directory in python ?

In this article we will discuss different APIs in python to create directories.

Creating a Directory in Python

Python’s OS module provides a function to create a directory i.e.

It creates a directory with given path i.e.

It creates the directory ‘tempDir’ in current directory.

Frequently Asked:

If directory already exists then it will raise FileExistsError Error. So to avoid errors either we should call it using try / except i.e.

# Create directory dirName = 'tempDir' try: # Create target Directory os.mkdir(dirName) print("Directory " , dirName , " Created ") except FileExistsError: print("Directory " , dirName , " already exists")

or we should first check if given folder exists or not i.e.

# Create target Directory if don't exist if not os.path.exists(dirName): os.mkdir(dirName) print("Directory " , dirName , " Created ") else: print("Directory " , dirName , " already exists")

os.mkdir(path) will create the given directory only, but it will not create the intermediate directory in the given path.

For example we want to create ‘temp/tempDir2/sample’ in current working directory. But neither temp or tempDir2 is present in current working directory. Hence it will throw error i.e.

dirName = 'tempDir2/temp2/temp' os.mkdir(dirName)
FileNotFoundError: [Errno 2] No such file or directory: 'tempDir2/temp2/temp'

os.mkdir(path) can not create intermediate directories in the given path,if they are not present. It will throws error in such cases. For that we need another API.

Creating Intermediate Directories in Python

Python’s OS module provides an another function to create a directories i.e.

os.makedirs(name) will create the directory on given path, also if any intermediate-level directory don’t exists then it will create that too.

Its just like mkdir -p command in linux.

Let’s create a directory with intermediate directories i.e.

dirName = 'tempDir2/temp2/temp' # Create target directory & all intermediate directories if don't exists os.makedirs(dirName)

It will create all the directory ‘temp’ and all its parent directories if they don’t exists.

If target directory already exists then it will throw error. So, either call it using try / except i.e.

# Create target directory & all intermediate directories if don't exists try: os.makedirs(dirName) print("Directory " , dirName , " Created ") except FileExistsError: print("Directory " , dirName , " already exists")

or before calling check if target directory already exists i.e.

# Create target directory & all intermediate directories if don't exists if not os.path.exists(dirName): os.makedirs(dirName) print("Directory " , dirName , " Created ") else: print("Directory " , dirName , " already exists")

Complete example is as follows,

import os def main(): # Create directory dirName = 'tempDir' try: # Create target Directory os.mkdir(dirName) print("Directory " , dirName , " Created ") except FileExistsError: print("Directory " , dirName , " already exists") # Create target Directory if don't exist if not os.path.exists(dirName): os.mkdir(dirName) print("Directory " , dirName , " Created ") else: print("Directory " , dirName , " already exists") dirName = 'tempDir2/temp2/temp' # Create target directory & all intermediate directories if don't exists try: os.makedirs(dirName) print("Directory " , dirName , " Created ") except FileExistsError: print("Directory " , dirName , " already exists") # Create target directory & all intermediate directories if don't exists if not os.path.exists(dirName): os.makedirs(dirName) print("Directory " , dirName , " Created ") else: print("Directory " , dirName , " already exists") if __name__ == '__main__': main()
Directory tempDir Created Directory tempDir already exists Directory tempDir2/temp2/temp Created Directory tempDir2/temp2/temp already exists

Источник

Читайте также:  Css иконка поверх изображения

Create a directory in Python

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. The os and os.path modules include many functions to interact with the file system. 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.

There are different methods available in the OS module for creating a director. These are –

Using os.mkdir()

os.mkdir() method in Python is used to create a directory named path with the specified numeric mode. This method raise FileExistsError if the directory to be created already exists.

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 directory to be created. If this parameter is omitted then default value Oo777 is used.
dir_fd (optional): A file descriptor referring to a directory. The default value of this parameter is None.
If the specified path is absolute then dir_fd is ignored. Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘dir_fd’) are keyword-only parameters and they can be provided using their name, not as positional parameter. Return Type: This method does not return any value.

Directory 'GeeksforGeeks' created Directory 'Geeks' created
Traceback (most recent call last): File "gfg.py", line 18, in os.mkdir(path) FileExistsError: [WinError 183] Cannot create a file when that file / /already exists: 'D:/Pycharm projects/GeeksForGeeks'
[WinError 183] Cannot create a file when that file/ /already exists: 'D:/Pycharm projects/GeeksForGeeks'

Using os.makedirs()

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:

D:/Pycharm projects/GeeksForGeeks/Authors/Nikhil

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

Читайте также:  Exception java getmessage null

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. Return Type: This method does not return any value.

Источник

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.

Читайте также:  Pipe string to python

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!

Источник

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