In Python, you can write JSON data to a file using the json module. Here's an example:
main.py234 chars14 lines
In this example, we import the json module, create a dictionary of sample data, and open a file called data.json for writing using the open() function. We then use the json.dump() method to write the JSON data to the file object.
Note that we used the with statement to open the file. This ensures that the file is automatically closed once the block of code inside the with statement is executed. It's good practice to use with when dealing with file I/O in Python.
To read data from a JSON file, you can use the json.load() function instead:
main.py203 chars10 lines
In this example, we open the data.json file for reading and use the json.load() function to read the JSON data from the file into a dictionary. We can then access the data from the dictionary as usual (in this case, we print the value associated with the name key).
gistlibby LogSnag