Python: How to create a new directory?

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() import os os.mkdir('myDirectory') 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 import os try: os.mkdir('myDirectory') print('myDirectory created') except FileExistsError: print('myDirectory already exists') If the directory does not exist: myDirectory created 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 import os print(os.getcwd()) Depending on the operating system the working directory is returned. /Users/username

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 import os os.mkdir('/Users/username/test2') 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() import os os.mkdir('/Users/username/test3', 0o755) 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 import os st = os.stat('/Users/username/test3') st_oct = oct(st.st_mode) print(st_oct) 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. 0o40755



Click to jump to section