Creating Directories using os.makedirs() in Python
In this tutorial, we are going to learn how we can create directories using os.makedirs() in Python. As we know, the OS module in Python helps us to interact with the operating system. All its functions are used to provide operating system dependent functionalities. In this post, we will learn about creating directories recursively using one of these functions.
os.makedirs() in Python
The syntax for os.makedirs() function is as follows:
os.makedirs(path [, mode, exist_ok])
In the above syntax, mode and exist_ok are optional. The default values for them are 0o777 and False. The function returns nothing.
Let’s say we want to create a directory named ‘codespeedy’ as follows:
C:\Users\Ranjeet Verma\Desktop\a\b\codespeedy
Now the problem is that directories a and b do not exist. This is where os.makedirs() function comes into play. This function creates all the missing directories in the given path. In this example, it will create directories a and b, and then it will create the directory with the name ‘codespeedy’.
Have a look at the given program and see how it works.
import os path = r'C:\Users\Ranjeet Verma\Desktop\a\b\codespeedy' os.makedirs(path) print('directory created')
Output:
directory created
After executing the above code, ‘codespeedy’ directory is created at the specified location.
When we try to create a directory that already exists at the given location using this function, an error is thrown. Let’s run the above code again and see what happens.
import os path = r'C:\Users\Ranjeet Verma\Desktop\a\b\codespeedy' os.makedirs(path) print('directory created')
Output:
Traceback (most recent call last): File "im.py", line 4, in <module> os.makedirs(path) File "C:\Users\Ranjeet Verma\Anaconda3\lib\os.py", line 221, in makedirs mkdir(name, mode) FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'C:\\Users\\Ranjeet Verma\\Desktop\\a\\b\\codespeedy'
Thank you.
Leave a Reply