Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # using files and JSON in Python
- # create a new text-file -> weekdays.txt
- Monday
- Tuesday
- Wednesday
- Thursday
- Friday
- Saturday
- Sunday
- # NEW FILE
- # open file and print the contents
- file_handle = open("weekdays.txt", "r")
- content = file_handle.read()
- print(content)
- # NEW FILE
- # open file and read it line by line
- file_handle = open("weekdays.txt", "r")
- counter = 1
- # as long as there are lines left, keep reading the line
- while True:
- line = file_handle.readline()
- # last line, break out of loop
- if not line:
- break
- # print the line
- print(f"{counter}. {line}")
- counter = counter + 1
- # NEW FILE
- # open file and print the contents
- file_handle = open("weekdays.txt", "r")
- content = file_handle.read()
- # split file content into a list!
- lines = content.split("\n")
- # how many lines in the file
- amount = len(lines)
- # go through each line of text
- for index in range(amount):
- line = lines[index]
- print(f"{index + 1}. {line}")
- # NEW FILE
- # open file and print the contents
- # "w" replaces all content in file
- file_handle = open("testing.txt", "w", encoding="utf-8")
- # ask a message from user
- message = input("Write down your message:\n")
- # write the message to a file
- file_handle.write(message)
- print("File saved!")
- # NEW FILE
- # open file and print the contents
- # "a" adds the new data after the previous data in file
- file_handle = open("testing.txt", "a", encoding="utf-8")
- # ask a message from user
- message = input("Write down your message:\n")
- # add a newline after the mssage so it goes
- # on another line in the file! otherwise
- # everything is appended on same line
- message = message + "\n"
- # write the message to a file
- file_handle.write(message)
- # it's a good idea to close the file connection
- # in order to prevent file lock in operating system, which
- # often requires a restart of the computer
- file_handle.close()
- print("File saved!")
- # create a new text file => city.json
- {
- "name":"Rovaniemi",
- "population":62933,
- "county":"Lapland"
- }
- # NEW FILE
- import json
- # open file and print the contents
- file_handle = open("city.json", "r")
- content = file_handle.read()
- data = json.loads(content)
- print(data['name'])
- print(data['population'])
- # NEW FILE
- import json
- # our data, dictionary
- phone = {
- "name": "Nokia 3310",
- "release_year": 2000,
- "battery": "1000mAh",
- "camera": False,
- "weight": 133
- }
- # open file in writing format
- # note: append -mode doesn't work with JSON
- # because it breaks the structure of JSON data!
- file_handle = open("phone.json", "w")
- # dictionary => JSON text
- data = json.dumps(phone)
- # save JSON text
- file_handle.write(data)
- file_handle.close()
- print("Phone was saved.")
- # create a new text file, cities.json
- [
- {
- "name": "Los Angeles",
- "population": 3898747,
- "state": "California"
- },
- {
- "name": "Miami",
- "population": 6166488,
- "state": "Florida"
- },
- {
- "name": "Denver",
- "population": 715522,
- "state": "Colorado"
- }
- ]
- # NEW FILE
- import json
- # load the json file contents
- file_handle = open("cities.json", "r")
- content = file_handle.read()
- # convert JSON string => Python list of dictionaries
- data = json.loads(content)
- # loop through all data (cities)
- for city in data:
- print(city['name'])
- print(city['population'])
- print()
- # BIG EXAMPLE, THIS READS A JSON FILE LIST AND ADDS NEW DATA INTO IT
- import json
- # load the json file contents
- file_handle = open("cities.json", "r")
- content = file_handle.read()
- file_handle.close()
- # convert JSON string => Python list of dictionaries
- data = json.loads(content)
- # loop through all data (cities)
- for city in data:
- print(city['name'])
- print(city['state'])
- print(city['population'])
- print()
- print()
- # let's add a new city, ask the info from user:
- city_name = input("New city, name:\n")
- city_population = input("New city, population:\n")
- city_state = input("New city, state:\n")
- # create a new dictionary
- new_city = {
- "name": city_name,
- "population": int(city_population),
- "state": city_state
- }
- # add new dictionary into existing list of cities
- data.append(new_city)
- # convert list of dictionaries => JSON text
- json_data = json.dumps(data)
- # open file for writing and write JSON text into file
- file_handle = open("cities.json", "w")
- file_handle.write(json_data)
- # close connection
- file_handle.close()
- # inform the user
- print("New city saved successfully!")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement