How to Read and Write File using Django?

Published On: 17/08/2022 | Category: Django

Hi Dev,

In this tute, we will discuss how to read and write file using django. you can understand a concept of how to read and write a file using python. you can understand a concept of how to read and write file using django project. I explained simply step by step how to read and write file using django in python. follow bellow step for read and write from a plain text in django.

So, django provides a file module django.core.files to handle files. This contains built-in classes for basic file handling. So, first we need to import this module package.

we have opened a file 'demo.txt' by providing its full path in the open method and giving the write mode argument

Follow bellow tutorial step of django read and write file example.

Example

In this example python open() function opens the file in the given mode argument, and the write() method is basically used to write a file, and the read() method is used to read a file. and last one is, we have closed the file object and file using close() method.

from django.shortcuts import render
from django.core.files import File
from django.http import HttpResponse

# Create your views here.

def writetofile(request):
    f = open('C:/demo/demo.txt', 'w')
    testfile = File(f)
    testfile.write('Welcome to Tuts-Station.com')
    testfile.close
    f.close
    return HttpResponse()

def readfile(request):
    f = open('C:/demo/demo.txt', 'r')
    if f.mode == 'r':
       contents =f.read()
       print (contents)
    return HttpResponse()  
Creating Urls

Next, we will require the modify the urls.py your root preoject folder lets update the file.

urls.py
from django.contrib import admin
from django.urls import path
from demoapp import views

urlpatterns = [
    path('file-write', views.writetofile),
    path('file-read', views.readfile),
]

I Hope It will help you....