Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Python, JSON and files, bigger example
- # REMEMBER TO CREATE cities.json first! (check Moodle or the materials for the list of american cities in JSON-format)
- import json
- # open the file, read content, close connection
- file_handle = open("cities.json", "r")
- content = file_handle.read()
- file_handle.close()
- # convert JSON (text) -> Python collection (list of dictionaries in this case)
- data = json.loads(content)
- # print out all cities we have
- for city in data:
- print(city['name'])
- print(city['state'])
- print(city['population'])
- print()
- # get the details of a new city from user
- city_name = input("New city, name: \n")
- city_state = input("New city, state:\n")
- city_population = input("New city, population:\n")
- # combine the given variables into a new dictionary
- new_city = {
- "name": city_name,
- "population": int(city_population),
- "state": city_state
- }
- # add the new city into the list of cities
- data.append(new_city)
- # convert the python data -> JSON text
- json_data = json.dumps(data)
- # open the file, rewrite the contents, close connection
- file_handle = open("cities.json", "w")
- file_handle.write(json_data)
- file_handle.close()
- print("New city saved successfully!")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement