Advertisement
tuomasvaltanen

Untitled

Dec 3rd, 2021
861
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.53 KB | None | 0 0
  1. # using files and JSON in Python
  2.  
  3. # create a new text-file -> weekdays.txt
  4.  
  5. Monday
  6. Tuesday
  7. Wednesday
  8. Thursday
  9. Friday
  10. Saturday
  11. Sunday
  12.  
  13. # NEW FILE
  14.  
  15. # open file and print the contents
  16. file_handle = open("weekdays.txt", "r")
  17. content = file_handle.read()
  18. print(content)
  19.  
  20. # NEW FILE
  21.  
  22. # open file and read it line by line
  23. file_handle = open("weekdays.txt", "r")
  24.  
  25. counter = 1
  26.  
  27. # as long as there are lines left, keep reading the line
  28. while True:
  29.     line = file_handle.readline()
  30.  
  31.     # last line, break out of loop
  32.     if not line:
  33.         break
  34.  
  35.     # print the line
  36.     print(f"{counter}. {line}")
  37.     counter = counter + 1
  38.  
  39. # NEW FILE
  40.  
  41. # open file and print the contents
  42. file_handle = open("weekdays.txt", "r")
  43. content = file_handle.read()
  44.  
  45. # split file content into a list!
  46. lines = content.split("\n")
  47.  
  48. # how many lines in the file
  49. amount = len(lines)
  50.  
  51. # go through each line of text
  52. for index in range(amount):
  53.     line = lines[index]
  54.     print(f"{index + 1}. {line}")
  55.  
  56.  
  57. # NEW FILE
  58.  
  59. # open file and print the contents
  60. # "w" replaces all content in file
  61. file_handle = open("testing.txt", "w", encoding="utf-8")
  62.  
  63. # ask a message from user
  64. message = input("Write down your message:\n")
  65.  
  66. # write the message to a file
  67. file_handle.write(message)
  68.  
  69. print("File saved!")
  70.  
  71. # NEW FILE
  72.  
  73. # open file and print the contents
  74. # "a" adds the new data after the previous data in file
  75. file_handle = open("testing.txt", "a", encoding="utf-8")
  76.  
  77. # ask a message from user
  78. message = input("Write down your message:\n")
  79.  
  80. # add a newline after the mssage so it goes
  81. # on another line in the file! otherwise
  82. # everything is appended on same line
  83. message = message + "\n"
  84.  
  85. # write the message to a file
  86. file_handle.write(message)
  87.  
  88. # it's a good idea to close the file connection
  89. # in order to prevent file lock in operating system, which
  90. # often requires a restart of the computer
  91. file_handle.close()
  92.  
  93. print("File saved!")
  94.  
  95. # create a new text file => city.json
  96.  
  97. {
  98.    "name":"Rovaniemi",
  99.    "population":62933,
  100.    "county":"Lapland"
  101. }
  102.  
  103. # NEW FILE
  104.  
  105. import json
  106.  
  107. # open file and print the contents
  108. file_handle = open("city.json", "r")
  109. content = file_handle.read()
  110.  
  111. data = json.loads(content)
  112. print(data['name'])
  113. print(data['population'])
  114.  
  115. # NEW FILE
  116.  
  117. import json
  118.  
  119. # our data, dictionary
  120. phone = {
  121.     "name": "Nokia 3310",
  122.     "release_year": 2000,
  123.     "battery": "1000mAh",
  124.     "camera": False,
  125.     "weight": 133
  126. }
  127.  
  128. # open file in writing format
  129. # note: append -mode doesn't work with JSON
  130. # because it breaks the structure of JSON data!
  131. file_handle = open("phone.json", "w")
  132.  
  133. # dictionary => JSON text
  134. data = json.dumps(phone)
  135.  
  136. # save JSON text
  137. file_handle.write(data)
  138. file_handle.close()
  139.  
  140. print("Phone was saved.")
  141.  
  142. # create a new text file, cities.json
  143.  
  144. [
  145.   {
  146.     "name": "Los Angeles",
  147.     "population": 3898747,
  148.     "state": "California"
  149.   },
  150.   {
  151.     "name": "Miami",
  152.     "population": 6166488,
  153.     "state": "Florida"
  154.   },
  155.   {
  156.     "name": "Denver",
  157.     "population": 715522,
  158.     "state": "Colorado"
  159.   }
  160. ]
  161.  
  162. # NEW FILE
  163.  
  164. import json
  165.  
  166. # load the json file contents
  167. file_handle = open("cities.json", "r")
  168. content = file_handle.read()
  169.  
  170. # convert JSON string => Python list of dictionaries
  171. data = json.loads(content)
  172.  
  173. # loop through all data (cities)
  174. for city in data:
  175.     print(city['name'])
  176.     print(city['population'])
  177.     print()
  178.  
  179.  
  180. # BIG EXAMPLE, THIS READS A JSON FILE LIST AND ADDS NEW DATA INTO IT
  181.  
  182. import json
  183.  
  184. # load the json file contents
  185. file_handle = open("cities.json", "r")
  186. content = file_handle.read()
  187. file_handle.close()
  188.  
  189. # convert JSON string => Python list of dictionaries
  190. data = json.loads(content)
  191.  
  192. # loop through all data (cities)
  193. for city in data:
  194.     print(city['name'])
  195.     print(city['state'])
  196.     print(city['population'])
  197.     print()
  198.  
  199. print()
  200.  
  201. # let's add a new city, ask the info from user:
  202. city_name = input("New city, name:\n")
  203. city_population = input("New city, population:\n")
  204. city_state = input("New city, state:\n")
  205.  
  206. # create a new dictionary
  207. new_city = {
  208.     "name": city_name,
  209.     "population": int(city_population),
  210.     "state": city_state
  211. }
  212.  
  213. # add new dictionary into existing list of cities
  214. data.append(new_city)
  215.  
  216. # convert list of dictionaries => JSON text
  217. json_data = json.dumps(data)
  218.  
  219. # open file for writing and write JSON text into file
  220. file_handle = open("cities.json", "w")
  221. file_handle.write(json_data)
  222.  
  223. # close connection
  224. file_handle.close()
  225.  
  226. # inform the user
  227. print("New city saved successfully!")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement