To write to a JSON file in Python, you can follow these steps:
open()
function to open a file in write mode. When opening the file, you can specify the name of the file and the file mode (w
for write mode).json.dump()
function to write the data to the file. This function takes two arguments: the data you want to write and the file object you want to write it to.close()
method on the file object.Here's an example code snippet:
main.py126 chars7 lines
In this example, we create a dictionary called data
with some key-value pairs. We then open a file called data.json
in write mode using a context manager (with
statement), and write the data to the file using the json.dump()
function. Finally, we close the file.
This will create a file called data.json
in the current working directory (where your Python script is located) with the following contents:
48 chars2 lines
Note that the json.dump()
function automatically converts the dictionary to a JSON string and writes it to the file. If you have a list of dictionaries, you can pass the list to the json.dump()
function instead of a single dictionary.
gistlibby LogSnag