How to create a new directory in Python?
There are several ways to create a new directory in Python.
create new directory using os.mkdir()
To create a new directory in Python, use the mkdir() method of the OS module in Python.
# create new directory using os.mkdir()
In case the directory already exists an FileExistsError exception will be raised.
Therefore it is recommended to call the mkdir() method within a try/except block.
using try/except block
Within the try block, specify the directory to be created. If the directory can not be created, the except block will be executed.
# create directory within try/except block
print('myDirectory already exists')
If the directory does not exist:
If directory exists:
myDirectory already exists
get current working directory
If not specified a new directory is created within the working directory. To get the current working directory, use the os.getcwd() method.
# get current working directory
Depending on the operating system the working directory is returned.
create directory in path
To create a new directory in a specific path it has to be specified in the os.mkdir() method.
# create directory in path
The directory test2 is created in the /Users/username/ path.
If the operations succeeds, nothing is returned.
If the operation files an exception is raised. For example if the directory already exists, it can't be created. In this case an FileExistsError exception is raised.
FileExistsError: [Errno 17] File exists: '/Users/users/test2'
access rights for creating directories
The access rights can be specified within the mkdir() function as optional argument.
The default value is 777, which makes the new directory readable and writable by the owner, group members and all other users.
# specify access rights of new directory using mkdir()
In this example the access rights are set to 755. This makes the the directory readable and accessible by all users and writeable only by the owner.
The user rights are written with octal prefix, to prevent the conversion of numbers to decimals.
check access rights of directory
To check the access rights of a directory, use the os.stat() method.
# check access rights of directory
st = os.stat('/Users/username/test3')
st_oct = oct(st.st_mode)
The os.stat() method returns an os.stat_result object. Then oct() is used to convert the st_mode attribute into numbers. Finally it is printed.
The last 3 numbers represent the access rights of the directory. In this example it is 755.