The os.mkdir()
method in Python is a function provided by the os
module that is used to create a new directory (folder) with the specified name. It allows you to programmatically create directories within your file system.
Here’s the official definition of os.mkdir()
:
import os
os.mkdir(path, mode=0o777, *, dir_fd=None)
import os
directory_path = '/path/to/new/directory'
os.mkdir(directory_path)
path
: A string that specifies the name and path of the directory you want to create.mode
(optional): An integer that sets the permissions for the newly created directory. The default value is0o777
, which gives read, write, and execute permissions to the owner, group, and others. You can specify a different mode using octal notation, such as0o755
or0o700
, depending on the desired permissions.dir_fd
(optional): Represents a file descriptor of the directory in which the new directory should be created. Ifdir_fd
is specified, thepath
parameter is treated as a relative path with respect to the directory represented bydir_fd
.
The os.mkdir()
method creates a directory at the specified path, relative to the current working directory unless an absolute path is provided. It raises an exception if the directory already exists, if there are permission issues, or if the path is invalid.
Note: the os.mkdir()
method only creates a single directory. If you want to create multiple directories, including any necessary parent directories, you can use os.makedirs()
instead
Python os.mkdir example
Here’s an example that demonstrates the usage of os.mkdir()
to create a directory:
import os
directory_name = "my_directory"
try:
os.mkdir(directory_name)
print(f"Directory '{directory_name}' created successfully!")
except FileExistsError:
print(f"Directory '{directory_name}' already exists!")
except Exception as e:
print(f"An error occurred: {str(e)}")
Output:
In this example:
- We import the
os
module. - We define the name of the directory we want to create as
directory_name
. - We use a
try-except
block to handle exceptions that may occur during the creation of the directory. - Inside the
try
block, we callos.mkdir(directory_name)
to create the directory. - If the directory is successfully created, we print a success message.
- If the directory already exists, a
FileExistsError
will be raised, and we print a corresponding message. - If any other exception occurs, we catch it using the generic
Exception
class, retrieve the error message usingstr(e)
, and print an error message.
Remember to replace "my_directory"
with the desired name of the directory you want to create.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.