To create a json file in Python, you can use the “with open()” expression. The “open()” function takes the file name and mode as an argument. If the file doesn’t exist, it will be created. The “with statement” is recommended for working with files because it assures that open file descriptors are closed automatically after program execution leaves the context of the with statement.
import json
with open('new_file.json', 'w') as f:
print("The json file is created")
Creating a json file from the existing json file in Python
To create a json file from an existing json file in Python, you can use the “open()” and with statement in write mode and dump the json data into a new json file.
{
"data": [
{
"color": "red",
"value": "#f00"
},
{
"color": "green",
"value": "#0f0"
},
{
"color": "blue",
"value": "#00f"
},
{
"color": "black",
"value": "#000"
}
]
}
Now, we will create a new json file from this data.json file.
import json
with open('data.json') as f:
data = json.load(f)
with open('new_file.json', 'w') as f:
json.dump(data, f, indent=2)
print("New json file is created from data.json file")
Output
New json file is created from data.json file
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.