Advertisement
tuomasvaltanen

Untitled

Nov 26th, 2024 (edited)
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.51 KB | None | 0 0
  1. # lecture 11, Introduction to Programming, basics of file management
  2. print("Welcome!")
  3.  
  4. # CREATE A NEW TEXTFILE, weekdays.txt, contents:
  5. Monday
  6. Tuesday
  7. Wednesday
  8. Thursday
  9. Friday
  10. Saturday
  11. Sunday
  12.  
  13. # NEW FILE
  14.  
  15. # open our text file
  16. file_handle = open("weekdays.txt", "r")
  17.  
  18. # load the content into a variable
  19. content = file_handle.read()
  20.  
  21. # print the content
  22. print(content)
  23.  
  24. # NEW FILE -> while-loop usually not the most practical
  25. # due to having to fix the extra new lines from the file
  26.  
  27. # open our text file
  28. file_handle = open("weekdays.txt", "r")
  29.  
  30. counter = 1
  31.  
  32. # infinite loop that keeps reading
  33. # the file line by line until we
  34. # arrive at the final row => we have the break out
  35. # of the loop
  36. while True:
  37.     # read one line at a time
  38.     line = file_handle.readline()
  39.     print(f"{counter}. {line}")
  40.  
  41.     # increase counter by one, shorthand
  42.     counter += 1
  43.  
  44.     if not line:
  45.         break
  46.  
  47.  
  48. # NEW FILE
  49.  
  50. # open our text file
  51. file_handle = open("weekdays.txt", "r")
  52.  
  53. # load the content into a variable
  54. content = file_handle.read()
  55.  
  56. # split the raw content of the file
  57. # into a list of rows (lines)
  58. lines = content.split("\n")
  59.  
  60. # get the amount of lines in this file
  61. amount = len(lines)
  62.  
  63. # based on the amount of lines
  64. # loop through the list of lines
  65. for index in range(amount):
  66.     # get the line and print a numbered list
  67.     line = lines[index]
  68.     print(f"{index + 1}. {line}")
  69.  
  70. # NEW FILE
  71.  
  72. # open the file for writing purposes
  73. # creates the file if it's missing (mynotes.txt)
  74. # we'll use UTF-8 as character encoding
  75. # in order to avoid garbled mess with Finnish Ä or Ö etc.
  76. file_handle = open("mynotes.txt", "w", encoding="utf-8")
  77.  
  78. # get the new text from user
  79. text = input("Write your message:\n")
  80.  
  81. file_handle.write(text)
  82.  
  83. print("Thank you for using our service.")
  84.  
  85. # NEW FILE, append-version
  86.  
  87. # open the file for writing purposes
  88. # creates the file if it's missing
  89. # we'll use UTF-8 as character encoding
  90. # in order to avoid garbled mess with Finnish Ä or Ö etc.
  91. file_handle = open("mynotes.txt", "a", encoding="utf-8")
  92.  
  93. # get the new text from user
  94. text = input("Write your message:\n")
  95.  
  96. # write the user's text at the end of the file
  97. # and add a new line in the end (so that our
  98. # data will place all new messages in their own rows)
  99. file_handle.write(text + "\n")
  100.  
  101. # let's close the file connection (good practice)
  102. file_handle.close()
  103.  
  104. print("Thank you for using our service.")
  105.  
  106. # NEW TEXT FILE: app_data.json , contents:
  107.  
  108. {
  109.   "name": "Rovaniemi",
  110.   "population": 62933,
  111.   "county": "Lapland"
  112. }
  113.  
  114. # NEW FILE
  115.  
  116. import json
  117.  
  118. # open the file and load the raw JSON data into a variable
  119. file_handle = open("app_data.json", "r")
  120. content = file_handle.read()
  121. file_handle.close()
  122.  
  123. # content is just the raw JSON in string format
  124. # JSON doesn't look like it, but it's actually text/string
  125.  
  126. # convert the raw JSON => Python data format
  127. # after this, we can use city -variable
  128. # as any other normal dictionary
  129. city = json.loads(content)
  130.  
  131. # you can use this to see that JSON is actually
  132. # just a string
  133. # import var_dump as vd
  134. # vd.var_dump(content)
  135. # vd.var_dump(content)
  136. # print()
  137. # vd.var_dump(city)
  138.  
  139. print("City details:")
  140. print("-------------")
  141. print(f"Name: {city['name']}")
  142. print(f"Population: {city['population']}")
  143. print(f"County / Municipality: {city['county']}")
  144.  
  145. # NEW FILE
  146.  
  147. import json
  148.  
  149. # this is our data in our code, dictionary
  150. phone = {
  151.     "name": "Nokia 3310",
  152.     "release_year": 2000,
  153.     "battery": "1000mAh",
  154.     "camera": False,
  155.     "weight": 133
  156. }
  157.  
  158. # we have to convert the complex Python data format into
  159. # raw JSON format (which is basically just text (serialization))
  160. # you can "prettify" the JSON data by using indent-parameter
  161. # e.g. content = json.dumps(phone, indent=2)
  162. content = json.dumps(phone)
  163.  
  164. # since content-variable is just text (JSON)
  165. # we can just save it to a file
  166. # always use w-mode with JSON data
  167. # since a-mode will break the syntax of JSON
  168. # making the data unusable
  169. file_handle = open("myphone.json", "w")
  170. file_handle.write(content)
  171. file_handle.close()
  172.  
  173. print("Thank you for adding your phone!")
  174.  
  175. # NEW TEXT FILE, cities.json, contents:
  176.  
  177. [
  178.   {
  179.     "name": "Finland",
  180.     "population": 5556146,
  181.     "capital": "Helsinki"
  182.   },
  183.   {
  184.     "name": "Sweden",
  185.     "population": 10402070,
  186.     "capital": "Stockholm"
  187.   },
  188.   {
  189.     "name": "France",
  190.     "population": 67413000,
  191.     "capital": "Paris"
  192.   }
  193. ]
  194.  
  195. # NEW FILE
  196.  
  197. import json
  198.  
  199. # open the raw JSON data -> r-mode
  200. file_handle = open("cities.json", "r")
  201. content = file_handle.read()
  202. file_handle.close()
  203.  
  204. # load all the countries in the file
  205. # into a list of dictionaries
  206. countries = json.loads(content)
  207.  
  208. # since our data is a list of dictionaries
  209. for country in countries:
  210.     # print(f"{country['name']})
  211.     print(f"{country['name']} ({country['capital']}) - population: {country['population']}")
  212.  
  213. # NEW TEXT FILE: americancities.json , contents:
  214.  
  215. [
  216.   {
  217.     "name": "Los Angeles",
  218.     "population": 3898747,
  219.     "state": "California"
  220.   },
  221.   {
  222.     "name": "Miami",
  223.     "population": 6166488,
  224.     "state": "Florida"
  225.   },
  226.   {
  227.     "name": "Denver",
  228.     "population": 715522,
  229.     "state": "Colorado"
  230.   }
  231. ]
  232.  
  233. # NEW FILE
  234.  
  235. import json
  236.  
  237. # PART 1: load up the original data and show the contents
  238.  
  239. file_handle = open("americancities.json", "r")
  240. content = file_handle.read()
  241. file_handle.close()
  242.  
  243. # convert raw JSON into Python format
  244. cities = json.loads(content)
  245.  
  246. # print the contents of the list
  247. for city in cities:
  248.     print(city['name'])
  249.     print(city['state'])
  250.     print(city['population'])
  251.     print()
  252.  
  253. print("--------------------------")
  254.  
  255. # PART 2: build a new city based on user's inputs
  256.  
  257. # gather three variables from user
  258. city_name = input("New city, name:\n")
  259.  
  260. # population as integer
  261. city_population = input("New city, population:\n")
  262. city_population = int(city_population)
  263.  
  264. city_state = input("New city, state:\n")
  265.  
  266. # finally create a new dictionary based on the variables
  267. new_city = {
  268.     "name": city_name,
  269.     "population": city_population,
  270.     "state": city_state
  271. }
  272.  
  273. # after we have a new dictionary => add the dictionary
  274. # into the list of cities
  275. cities.append(new_city)
  276.  
  277. # PART 3: save the new version of the cities list
  278. # into the JSON file (override)
  279. json_data = json.dumps(cities, indent=2)
  280.  
  281. # save the new version back into the file
  282. file_handle = open("americancities.json", "w")
  283. file_handle.write(json_data)
  284. file_handle.close()
  285.  
  286. print("Thank you for adding a new city into the data!")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement