Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # files and JSON in Python
- # create file weekdays.txt:
- Monday
- Tuesday
- Wednesday
- Thursday
- Friday
- Saturday
- Sunday
- # reading a file
- file_handle = open("weekdays.txt", "r")
- content = file_handle.read()
- print(content)
- # NEW FILE
- file_handle = open("weekdays.txt", "r")
- counter = 1
- # process the file
- while True:
- # next line
- line = file_handle.readline()
- # end of file
- if not line:
- break
- # print the line
- print(f"{counter} : {line}")
- counter = counter + 1
- # NEW FILE
- # open the file
- file_handle = open("weekdays.txt", "r")
- # load the content of the file into a variable
- content = file_handle.read()
- # split content into a list of texts
- lines = content.split("\n")
- # how many lines
- amount = len(lines)
- # loop through lines, numbered list
- for index in range(amount):
- line = lines[index]
- print(f"{index + 1}. {line}")
- # NEW FILE
- # open file, force to use utf-8 in order to see special characters etc. correctly
- # also important if using different languages that involve other characters
- # than in standard English
- file_handle = open("testing.txt", "w", encoding="utf-8")
- text = input("Write your message:\n")
- # file_handle.write("Is this still working?")
- file_handle.write(text)
- print("File saved.")
- # create a city.json -file:
- {
- "name":"Rovaniemi",
- "population":62933,
- "county":"Lapland"
- }
- # NEW FILE
- import json
- # open the file, read content, close connection
- file_handle = open("city.json", "r")
- content = file_handle.read()
- file_handle.close()
- # convert JSON text => Python dictionary (or list, depends on data)
- data = json.loads(content)
- # data is now a dictionary, use as you wish
- print(data['name'])
- print(data['population'])
- # NEW FILE
- import json
- phone = {
- "name": "Nokia 3310",
- "release_year": 2000,
- "battery": "1000mAh",
- "camera": False,
- "weight": 133
- }
- file_handle = open("phone.json", "w")
- #print(phone)
- data = json.dumps(phone)
- file_handle.write(data)
- file_handle.close()
- print("The phone was saved.")
- # first create cities.json -file:
- [
- {
- "name": "Los Angeles",
- "population": 3898747,
- "state": "California"
- },
- {
- "name": "Miami",
- "population": 6166488,
- "state": "Florida"
- },
- {
- "name": "Denver",
- "population": 715522,
- "state": "Colorado"
- }
- ]
- # NEW FILE
- import json
- # open the file, read content, close connection
- file_handle = open("cities.json", "r")
- content = file_handle.read()
- file_handle.close()
- data = json.loads(content)
- for city in data:
- print(city['name'])
Add Comment
Please, Sign In to add comment