copy a json file in python

To copy a JSON file in Python, you can read the contents of the file, parse it using the json module, and write the parsed data to a new file.

Assuming that you have a JSON file named input.json in the same directory as your Python script, the following code will create a copy of the file named output.json:

main.py
import json

# open the input file and parse the JSON data
with open('input.json', 'r') as f:
    data = json.load(f)

# write the parsed data to the output file
with open('output.json', 'w') as f:
    json.dump(data, f)
221 chars
10 lines

This code reads the contents of input.json and parses it into a Python dictionary using json.load(). It then writes the dictionary back to a new file output.json using json.dump(). Note that this code assumes that the contents of the input file are valid JSON data. If the contents are invalid or malformed, this code will likely raise a JSONDecodeError.

gistlibby LogSnag