Advertisement
tuomasvaltanen

Untitled

Dec 7th, 2021 (edited)
732
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.22 KB | None | 0 0
  1. # Python, JSON and files, bigger example
  2.  
  3. # REMEMBER TO CREATE cities.json first! (check Moodle or the materials for the list of american cities in JSON-format)
  4.  
  5. import json
  6.  
  7. # open the file, read content, close connection
  8. file_handle = open("cities.json", "r")
  9. content = file_handle.read()
  10. file_handle.close()
  11.  
  12. # convert JSON (text) -> Python collection (list of dictionaries in this case)
  13. data = json.loads(content)
  14.  
  15. # print out all cities we have
  16. for city in data:
  17.     print(city['name'])
  18.     print(city['state'])
  19.     print(city['population'])
  20.     print()
  21.  
  22.  
  23. # get the details of a new city from user
  24. city_name = input("New city, name: \n")
  25. city_state = input("New city, state:\n")
  26. city_population = input("New city, population:\n")
  27.  
  28. # combine the given variables into a new dictionary
  29. new_city = {
  30.     "name": city_name,
  31.     "population": int(city_population),
  32.     "state": city_state
  33. }
  34.  
  35. # add the new city into the list of cities
  36. data.append(new_city)
  37.  
  38. # convert the python data -> JSON text
  39. json_data = json.dumps(data)
  40.  
  41. # open the file, rewrite the contents, close connection
  42. file_handle = open("cities.json", "w")
  43. file_handle.write(json_data)
  44. file_handle.close()
  45.  
  46. print("New city saved successfully!")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement