Create a directory if it does not exist in Django

In this tutorial, we will check if the directory exists or not, if it doesn’t exist then we will create one. Python allows interacting with the operating system using module os. There is a module named isdir() and makedirs() to check and create a directory. We will complete this task by using an if-else condition statement. The If part will check if the directory exists if it doesn’t exist it will create in else part.

  1. Start by creating a project.
  2. Next, start an app.

Check if a directory exists otherwise create one.

You have started a project and an app, we need to follow certain steps to check and create.

Open your urls.py and define URL to execute the function under views.py

path("",views.create_dir),

urls.py file-

from django.contrib import admin
from django.urls import path
from app import views as views

urlpatterns = [
    path('admin/', admin.site.urls),
    path("",views.create_dir),
]

You just need to create a function in views.py under your app as-

def create_dir(request):
    directory_name="codespeedy"
    if os.path.isdir(directory_name):
        return HttpResponse("Exists")
    else:
        os.makedirs(directory_name)
        return HttpResponse("Created")

Import os, from os import path and also HttpResponse.

views.py looks like-

def create_dir(request):
    directory_name="codespeedy"
    if os.path.isdir(directory_name):
        return HttpResponse("Exists")
    else:
        os.makedirs(directory_name)
        return HttpResponse("Created")

Run python manage.py runserver in your terminal.

You will see the output screen as-

Create a directory if it does not exist in Django

You will only be able to see this type of screen if a directory doesn’t exist

The next time you run the server or refresh the screen would look like this-

Create a directory if it does not exist in Django

Also, you can navigate into the directory to check if it has been successfully created or not.

This was a complete tutorial to check if a directory exists or not, and also if it doesn’t exist, it will create one for us.

Thank you for reading! I hope this tutorial was helpful in any way! Feel free to comment and share your reviews.

Leave a Reply

Your email address will not be published.