I want to run mkdir
command as:
mkdir -p directory_name
What's the method to do that in Python?
os.mkdir(directory_name [, -p]) didn't work for me.
Python method mkdir() create a directory named path with numeric mode mode. The default mode is 0777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out.
Os. mkdir() method is used in python to try to create a path with a numeric mode. Note: The method gives FileExistsError if the path already exists. path is the path where you want to complete the new directory.
To find the current working directory in Python, use os. getcwd() , and to change the current working directory, use os. chdir(path) .
Creating a directory is a common operation in Python when you're working with files. The os. mkdir() method can be used to create a single directory, and the os. makedirs() method can be used to create multi-level directories.
Python os.mkdir() Method. Description. Python method mkdir() create a directory named path with numeric mode mode. The default mode is 0777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out.
That means while making leaf directory if any intermediate-level directory is missing, os.makedirs () method will create them all. Suppose we want to create directory ‘ihritik’ but Directory ‘GeeksForGeeks’ and ‘Authors’ are unavailable in the path. Then os.makedirs () method will create all unavailable/missing directory in the specified path.
The default mode is 0777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out. Following is the syntax for mkdir () method − path − This is the path, which needs to be created. mode − This is the mode of the directories to be given.
In Python, we can build a directory by using the mkdir method. It is a commonly used method provided by the OS module for connecting with operating systems. It can be declared or defined in Python as the os.mkdir () method which creates folders with a numeric mode and path as inputs.
You can try this:
# top of the file
import os
import errno
# the actual code
try:
os.makedirs(directory_name)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(directory_name):
pass
According to the documentation, you can now use this since python 3.2
os.makedirs("/directory/to/make", exist_ok=True)
and it will not throw an error when the directory exists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With