How do create, read, update and delete (CRUD) files in Django?
CRUD is an acronym that stands for Create, Read, Update, and Delete. These are the four basic operations performed on Database Models. We are creating code snippets to carry out these operations.
In Django, you can use the built-in Python functions or you can use default_storage
to create, read, update, and delete files.
The built-in Python functions
Here are a few examples of how you can use the built-in Python functions to create, read, update, and delete a file in Django:
import os # Create a file with open('myfile.txt', 'w') as f: f.write('Hello, world!') # Read a file with open('myfile.txt', 'r') as f: contents = f.read() print(contents) # Update a file with open('myfile.txt', 'w') as f: f.write('Hello, world! How are you today?') # Delete a file os.remove('myfile.txt') # Check if a file exists if os.path.exists('myfile.txt'): print("The file exists.") else: print("The file does not exist.") # Check if a file is readable if os.access('myfile.txt', os.R_OK): print("The file is readable.") else: print("The file is not readable.") # Check if a file is writable if os.access('myfile.txt', os.W_OK): print("The file is writable.") else: print("The file is not writable.")
How did the above examples work?
This code will:
- Create a file called
myfile.txt
- Write the text “Hello, world!” to it
- Read the contents of the file and print it to the screen
- Update the contents of the file to “Hello, world! How are you today?”
- Delete the file
- Check if the file exists
- Check if the file is readable and writable
The File storage
In Django, it is generally recommended to use the default_storage provided by Django to manage files. This allows you to easily switch between different storage backends, such as a local disk or a cloud storage service. You can use default_storage
to create, read, update, and delete files in Django as follows:
from django.core.files.storage import default_storage # Create a file default_storage.save('myfile.txt', 'Hello, world!') # Read a file with default_storage.open('myfile.txt', 'r') as f: contents = f.read() print(contents) # Update a file default_storage.save('myfile.txt', 'Hello, world! How are you today?') # Delete a file default_storage.delete('myfile.txt') # Check if a file exists if default_storage.exists('myfile.txt'): print("The file exists.") else: print("The file does not exist.")