Django Read and Write Text File Example

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

Hi Dev,

This article will provide example of django read and write text file example. This article will give you simple example of how to read and write a text file using python. This tutorial will give you simple example of how to read and write text file using django. we will help you to give example of how to read and write text file using django in python.

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 text 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 text file example.

Example

In this example python open() function opens the text file in the given mode argument, and the write() method is basically used to write a text file, and the read() method is used to read a text 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....