Python open create directory

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.

Читайте также:  Нет формата ввода php

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.

Читайте также:  Java работа с комплексными числами

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.

Читайте также:  Java security invalidkeyexception parameters missing

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!

Источник

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