Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # lecture 11, Introduction to Programming, basics of file management
- print("Welcome!")
- # CREATE A NEW TEXTFILE, weekdays.txt, contents:
- Monday
- Tuesday
- Wednesday
- Thursday
- Friday
- Saturday
- Sunday
- # NEW FILE
- # open our text file
- file_handle = open("weekdays.txt", "r")
- # load the content into a variable
- content = file_handle.read()
- # print the content
- print(content)
- # NEW FILE -> while-loop usually not the most practical
- # due to having to fix the extra new lines from the file
- # open our text file
- file_handle = open("weekdays.txt", "r")
- counter = 1
- # infinite loop that keeps reading
- # the file line by line until we
- # arrive at the final row => we have the break out
- # of the loop
- while True:
- # read one line at a time
- line = file_handle.readline()
- print(f"{counter}. {line}")
- # increase counter by one, shorthand
- counter += 1
- if not line:
- break
- # NEW FILE
- # open our text file
- file_handle = open("weekdays.txt", "r")
- # load the content into a variable
- content = file_handle.read()
- # split the raw content of the file
- # into a list of rows (lines)
- lines = content.split("\n")
- # get the amount of lines in this file
- amount = len(lines)
- # based on the amount of lines
- # loop through the list of lines
- for index in range(amount):
- # get the line and print a numbered list
- line = lines[index]
- print(f"{index + 1}. {line}")
- # NEW FILE
- # open the file for writing purposes
- # creates the file if it's missing (mynotes.txt)
- # we'll use UTF-8 as character encoding
- # in order to avoid garbled mess with Finnish Ä or Ö etc.
- file_handle = open("mynotes.txt", "w", encoding="utf-8")
- # get the new text from user
- text = input("Write your message:\n")
- file_handle.write(text)
- print("Thank you for using our service.")
- # NEW FILE, append-version
- # open the file for writing purposes
- # creates the file if it's missing
- # we'll use UTF-8 as character encoding
- # in order to avoid garbled mess with Finnish Ä or Ö etc.
- file_handle = open("mynotes.txt", "a", encoding="utf-8")
- # get the new text from user
- text = input("Write your message:\n")
- # write the user's text at the end of the file
- # and add a new line in the end (so that our
- # data will place all new messages in their own rows)
- file_handle.write(text + "\n")
- # let's close the file connection (good practice)
- file_handle.close()
- print("Thank you for using our service.")
- # NEW TEXT FILE: app_data.json , contents:
- {
- "name": "Rovaniemi",
- "population": 62933,
- "county": "Lapland"
- }
- # NEW FILE
- import json
- # open the file and load the raw JSON data into a variable
- file_handle = open("app_data.json", "r")
- content = file_handle.read()
- file_handle.close()
- # content is just the raw JSON in string format
- # JSON doesn't look like it, but it's actually text/string
- # convert the raw JSON => Python data format
- # after this, we can use city -variable
- # as any other normal dictionary
- city = json.loads(content)
- # you can use this to see that JSON is actually
- # just a string
- # import var_dump as vd
- # vd.var_dump(content)
- # vd.var_dump(content)
- # print()
- # vd.var_dump(city)
- print("City details:")
- print("-------------")
- print(f"Name: {city['name']}")
- print(f"Population: {city['population']}")
- print(f"County / Municipality: {city['county']}")
- # NEW FILE
- import json
- # this is our data in our code, dictionary
- phone = {
- "name": "Nokia 3310",
- "release_year": 2000,
- "battery": "1000mAh",
- "camera": False,
- "weight": 133
- }
- # we have to convert the complex Python data format into
- # raw JSON format (which is basically just text (serialization))
- # you can "prettify" the JSON data by using indent-parameter
- # e.g. content = json.dumps(phone, indent=2)
- content = json.dumps(phone)
- # since content-variable is just text (JSON)
- # we can just save it to a file
- # always use w-mode with JSON data
- # since a-mode will break the syntax of JSON
- # making the data unusable
- file_handle = open("myphone.json", "w")
- file_handle.write(content)
- file_handle.close()
- print("Thank you for adding your phone!")
- # NEW TEXT FILE, cities.json, contents:
- [
- {
- "name": "Finland",
- "population": 5556146,
- "capital": "Helsinki"
- },
- {
- "name": "Sweden",
- "population": 10402070,
- "capital": "Stockholm"
- },
- {
- "name": "France",
- "population": 67413000,
- "capital": "Paris"
- }
- ]
- # NEW FILE
- import json
- # open the raw JSON data -> r-mode
- file_handle = open("cities.json", "r")
- content = file_handle.read()
- file_handle.close()
- # load all the countries in the file
- # into a list of dictionaries
- countries = json.loads(content)
- # since our data is a list of dictionaries
- for country in countries:
- # print(f"{country['name']})
- print(f"{country['name']} ({country['capital']}) - population: {country['population']}")
- # NEW TEXT FILE: americancities.json , contents:
- [
- {
- "name": "Los Angeles",
- "population": 3898747,
- "state": "California"
- },
- {
- "name": "Miami",
- "population": 6166488,
- "state": "Florida"
- },
- {
- "name": "Denver",
- "population": 715522,
- "state": "Colorado"
- }
- ]
- # NEW FILE
- import json
- # PART 1: load up the original data and show the contents
- file_handle = open("americancities.json", "r")
- content = file_handle.read()
- file_handle.close()
- # convert raw JSON into Python format
- cities = json.loads(content)
- # print the contents of the list
- for city in cities:
- print(city['name'])
- print(city['state'])
- print(city['population'])
- print()
- print("--------------------------")
- # PART 2: build a new city based on user's inputs
- # gather three variables from user
- city_name = input("New city, name:\n")
- # population as integer
- city_population = input("New city, population:\n")
- city_population = int(city_population)
- city_state = input("New city, state:\n")
- # finally create a new dictionary based on the variables
- new_city = {
- "name": city_name,
- "population": city_population,
- "state": city_state
- }
- # after we have a new dictionary => add the dictionary
- # into the list of cities
- cities.append(new_city)
- # PART 3: save the new version of the cities list
- # into the JSON file (override)
- json_data = json.dumps(cities, indent=2)
- # save the new version back into the file
- file_handle = open("americancities.json", "w")
- file_handle.write(json_data)
- file_handle.close()
- print("Thank you for adding a new city into the data!")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement