Python Create Directory

Python Create Directory

Python makes you able to interact with the operating system using the in-built OS module. You already know that you can read or write data in the file system, but Python is not limited to only that.

The os and os.path contain various useful functions that make you able to interact with the file system.

Before we start this tutorial, let’s discuss few points about the usability of the functions provided in the module. Here they are:

  1. As long as the functionality by the operating system is available, the modules that depend on the operating software use the same interface provided by the operating system.

  2. The OS module provides some extensions that are specific to a certain operating system, but it would be a potential threat to portability if you use them.

All the functions that accept path or file names always accept both string and bytes objects. Also, they will produce an output that would be of string and bytes object too

Let’s begin this tutorial and learn how to use OS module’s functions to create directories and other useful but basic stuff!

Getting the Working Directory

A working directory is the directory that is currently active. In other words, it is the directory in which you are coding and running your Python project file.

Knowing the working directory can be a hassle sometimes. This hassle can be easily solved using the getcwd() method from the os module.

Example

Python Getting the working directory

We uses PyCharm IDE, it will shows the working directory everytime we execute the code. That might not be the case for you if you are not using PyCharm, so this function can be useful for you.

Now, for creating directories, the OS module provides two important methods to do that:

  1. mkdir()
  2. makedirs()

mkdir() method

mkdir() method can create a single directory at a single time. To create multiple sub-directories, you would have to call this function again and again.

Syntax: mkdir(path, mode=0o777, *, dir_fd = None)

Meaning of Parameters:

  • path: This the path of the directory that you want to create in your operating system.
  • mode: This is an optional mode specifies the representing mode of the directory that you want to create. Some systems ignore this parameter.
  • *: It tells Python that all of the parameters that follow this parameter can only be passed using their name.

    In other words, the parameters cannot be positional parameters. In the case of mkdir(), that parameter is dir_fd.

  • dir_fd: This is also an optional parameter. It is an abstract handle indicating a directory. Default value is None, and this parameter is ignored by Python if the path of your file is absolute.

Bonus Tips

  • Creating multiple directories at once is the task assigned to the makedirs() method.

Here is how you can create a directory using the mkdir() method. First, you have to import the os module to access this method.

Example

Python Create Directory - mkdir() method

Let’s understand the code:

  1. To create a new directory, you have to write the full path of that folder in your OS. In the above example, we want to create a folder named “NewFolder”.
    We store this information in a variable named “new_path”.

  2. Then we call the mkdir() function from the OS module using the dot separator, and pass the variable in which you stored your path.

Errors While Creating Directories

If you run the code above again to create the same folder named “NewFolder” in the same directory, you will get an error.

Example

Python- mkdir() - Errors While Creating Directories

Also, if the path that you have specified, then Python will raise the FileNotFoundError. So be cautious of directory names and paths while using this module.

Handling Errors While Creating Directories

The errors discussed above are of type OSError, therefore they can be easily tackled using the try-except block as shown below:

Example

Python Create Directory - makedirs() method - Handling Errors

Changing mode Parameter

The default value of the mode parameter is 0o777, which basically means that the newly created folder is both writable and readable by all users of the system (of course including the owner).

However, this default setting can be changed, for example, if you want to make the new directory writable only by the owner of the system, then set the value of mode equal to 0o755.

Example

Python Create Directory - mkdir() - Changing mode Parameter

Now, if someone else logins as a different user in your laptop, they won’t be able to write anything in the created folder. This increases the security!

makedirs() method

You can create multiple directories too using the makedirs()  method. makedirs() method from the OS module uses recursion to create new directories.

Syntax:os.makedirs(path, mode=0o777, exist_ok=False)

Meaning of Parameters:

  • exist_ok: This is an optional parameter. It will raise an error if the directory that you want to create already exists you should leave it to its default value. By default it is equal to False.
    Set the value equal to True if you do not want an error if the directory already exists.

This method will create all directories that do not exist specified in the path.

Example

Python - makedirs() method

Let’s understand the code:

  1. The folders: NewTutorial, Folder, and SubFolder do not exist in the system. So when we executed this code, the makedirs() created all of the folders that were non-existent!

Handling Errors in makedirs() method

This method also raises the OSError whenever it finds an already existent path. For example, if you run the code above again, the method will return the same error as the mkdir() function.

Let’s use the try-except block to handle the error.

Example

Python Create Directory - makedirs() method - Handling Errors

Example

Python - makedirs() method - Handling Errors in makedirs()

Conclusion

Creating new directories and file handling in Python is very easy. You only need to read to write just a simple code block to do so!

Tutorials for all brains!