Published on January 26, 2024By DeveloperBreeze
import json
# Define the JSON file to read and write
json_file = 'list.json'
# Read the existing JSON data
try:
with open(json_file, 'r') as file:
json_list = json.load(file)
print("Successfully loaded the JSON file.")
except FileNotFoundError:
print(f"File '{json_file}' not found. Initializing with an empty list.")
json_list = []
except json.JSONDecodeError:
print(f"File '{json_file}' is not a valid JSON file. Initializing with an empty list.")
json_list = []
# New data to add to the JSON
new_entry = {'Name': 'The Good Coder', 'Hobbies': 'Code, Write Code!'}
# Append the new data to the JSON list
json_list.append(new_entry)
print("New entry added to the JSON list.")
# Write the updated list back to the JSON file
with open(json_file, 'w') as file:
json.dump(json_list, file, indent=4)
print(f"Updated JSON data written to '{json_file}'.")
Comments
Please log in to leave a comment.