How to read and write a file using Django
In this article, you will learn how to read and write file using the Django.
Django is a free, open-source, Python-based framework. It enables fast development of any type of web application. It is secure, maintainable, portable and scalable. The main advantages of using Django are that it has fully loaded common web development tasks, like administration, authentication, site maps etc.
Django File Object
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-
from django.core.files import File
The open() function opens the file in the given mode argument, and the write() method is used to write a file, and the read() method is used to read a file. At last, we have closed the file object and file using the close() method.
Here is the complete code to write and read a file. First, we have opened the file 'text.txt' by providing its full path in the open method and giving the write mode argument. The same file is then opened in read mode.
views.py
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/test.txt', 'w')
testfile = File(f)
testfile.write('Welcome to this country')
testfile.close
f.close
return HttpResponse()
def readfile(request):
f = open('C:/demo/test.txt', 'r')
if f.mode == 'r':
contents =f.read()
print (contents)
return HttpResponse()
urls.py
At last, we have added a path to route the page to a particular link.
from django.contrib import admin
from django.urls import path
from demoapp import views
urlpatterns = [
path('filewrite', views.writetofile),
path('readfile', views.readfile),
]
When you open 'http://127.0.0.1:8000/filewrite' on the browser, it writes the given text on the file, and on calling 'http://127.0.0.1:8000/readfile', it reads the file content and displays it in the console.
Related Articles
Django ajax GET and POST requestDjango Pagination with Ajax and jQuery
Django upload image to database
How to read and write a file using Django
Django pass variable from view to HTML template
Django Export Model Data to CSV
How to generate and download CSV file in Django
How to get data from MySQL in Django View with Models
Django Send Mail on Contact form submission
How to insert data in MySQL database from an HTML form using Django
How to generate QR Code in Python using PyQRCode
Python programs to check Palindrome strings and numbers
CRUD operations in Python using MYSQL Connector
Fibonacci Series Program in Python
Find the stop words in nltk Python
Python OpenCV Image Filtering
Eye Detection Program in Python OpenCV
Arithmetic Operations on Images using Python OpenCV