So today I’m gonna teach you about the “dump” and “load” functions in the JSON module in Python.
First, you have to import.
from json import dump, load
Now, we’re gonna learn about “dumping”
So “dump” is a function in JSON which can add contents in a file
Here’s an example:
file = open("file_name.json", "w")
dump("file contents", file)
What that does is make a file (if it doesn’t exist already) with “file contents” inside it.
The file contents don’t have to be a string. It can a integer, floating point, list, and basically everything (as long as it’s an object).
There are 3 ways to “dump”
replace_file_contents = open("file_name.json", "w")
add_to_file_contents = open("file_name.json", "a")
create_file = open("file_name.json", "x")
# This creates a file (if it already exists, then you will get a FileExistsError)
dump(123, create_file)
# This replaces the contents of a file (if the file doesn't exist, then the program will create a new file)
dump(True, replace_file_contents)
# This adds content to the file (if the file doesn't exist, then the program will create a new file)
dump("string", add_to_file_contents)
Now we’re going to talk about “load”.
It is used to read files.
Here’s an example:
variable = load(open("file_name.json"))
That’s all for now, Bye!