import csv
import json
import csv
exampleFile = open('Docs/D2_01.csv')
exampleReader = csv.reader(exampleFile)
exampleData = list(exampleReader)
exampleData
[['DateTime', 'Name', 'Age', 'Sex'], ['2018/1/1', 'Olly', '13', 'F'], ['2018/1/2', 'Ollier', '14', 'F'], ['2018/1/3', 'Oil', '12', 'M'], ['2018/1/4', 'Oba', '16', 'F'], ['2018/1/5', 'Oma', '17', 'M'], ['2018/1/6', 'Ohya', '18', 'F']]
exampleData[1][1]
'Olly'
exampleData[2][1]
'Ollier'
exampleData[6][2]
'18'
import csv
exampleFile = open('Docs/D2_01.csv')
exampleReader = csv.reader(exampleFile)
for row in exampleReader:
print(row)
['DateTime', 'Name', 'Age', 'Sex'] ['2018/1/1', 'Olly', '13', 'F'] ['2018/1/2', 'Ollier', '14', 'F'] ['2018/1/3', 'Oil', '12', 'M'] ['2018/1/4', 'Oba', '16', 'F'] ['2018/1/5', 'Oma', '17', 'M'] ['2018/1/6', 'Ohya', '18', 'F']
import csv
exampleFile = open('Docs/D2_01.csv')
exampleReader = csv.reader(exampleFile)
for row in exampleReader:
print('Row #' + str(exampleReader.line_num) + ' ' + str(row))
Row #1 ['DateTime', 'Name', 'Age', 'Sex'] Row #2 ['2018/1/1', 'Olly', '13', 'F'] Row #3 ['2018/1/2', 'Ollier', '14', 'F'] Row #4 ['2018/1/3', 'Oil', '12', 'M'] Row #5 ['2018/1/4', 'Oba', '16', 'F'] Row #6 ['2018/1/5', 'Oma', '17', 'M'] Row #7 ['2018/1/6', 'Ohya', '18', 'F']
import csv
outputFile = open('Docs/D2_02.csv', 'w', newline='')
outputWriter = csv.writer(outputFile)
outputWriter.writerow(['dog', 'cat', 'bird'])
outputWriter.writerow(['Hi, dog!', 'cat', 'bird'])
outputWriter.writerow([1, 2, 3.14])
outputFile.close()
import csv
outputFile = open('Docs/D2_03.csv', 'w')
outputWriter = csv.writer(outputFile)
outputWriter.writerow(['dog', 'cat', 'bird'])
outputWriter.writerow(['Hi, dog!', 'cat', 'bird'])
outputWriter.writerow([1, 2, 3.14])
outputFile.close()
import csv
outputFile = open('Docs/D2_04.tsv', 'w', newline='')
outputWriter = csv.writer(outputFile, delimiter='\t')
outputWriter.writerow(['dog', 'cat', 'bird'])
outputWriter.writerow(['Hi, dog!', 'cat', 'bird'])
outputWriter.writerow([1, 2, 3.14])
outputFile.close()
JasonString1 = '{"name": "Olly", "Female": true, "Height": 154, "Weight": null}'
type(JasonString1)
str
import json
JasonAsPyValue =json.loads(JasonString1)
JasonAsPyValue
{'Female': True, 'Height': 154, 'Weight': None, 'name': 'Olly'}
type(JasonAsPyValue)
dict
PyDict = {'Female': False, 'Height': None, 'Weight': 50, 'name': 'Ohbo'}
type(PyDict)
dict
import json
PyDictAsJason = json.dumps(PyDict)
PyDictAsJason
'{"Height": null, "Female": false, "name": "Ohbo", "Weight": 50}'
type(PyDictAsJason)
str
import json, requests
url = 'http://api.openweathermap.org/data/2.5/weather?q=%s&APPID=%s' %(location, APPID)
response = requests.get(url)
response.raise_for_status()
weatherData = json.loads(response.text)
weatherData.keys()
dict_keys(['cod', 'id', 'visibility', 'base', 'weather', 'clouds', 'wind', 'dt', 'coord', 'sys', 'name', 'main'])
weatherData
{'cod': 200, 'id': 1668341, 'visibility': 10000, 'base': 'stations', 'weather': [{'main': 'Clouds', 'icon': '04n', 'description': 'broken clouds', 'id': 803}], 'clouds': {'all': 75}, 'wind': {'speed': 3.1, 'deg': 80}, 'dt': 1509365100, 'coord': {'lon': 121.53, 'lat': 25.05}, 'sys': {'message': 0.0085, 'type': 1, 'country': 'TW', 'id': 7479, 'sunrise': 1509314416, 'sunset': 1509354862}, 'name': 'Taipei', 'main': {'temp_min': 292.15, 'pressure': 1023, 'humidity': 68, 'temp': 292.6, 'temp_max': 293.15}}
city = weatherData['name']
dt = weatherData['dt']
weather = weatherData['weather'][0]
city
'Taipei'
import datetime
dtime = datetime.datetime.fromtimestamp(dt).strftime('%Y-%m-%d %H:%M:%S')
dtime
'2017-10-30 20:05:00'
w_main = weather['main']
w_main
'Clouds'
w_desc = weather['description']
w_desc
'broken clouds'
print('~~ Current Wheather ~~')
print('★ Location :\t', city)
print('★ Date Time :\t', dtime)
print('★ Weather :\t', w_main, '-', w_desc)
~~ Current Wheather ~~ ★ Location : Taipei ★ Date Time : 2017-10-30 20:05:00 ★ Weather : Clouds - broken clouds
import csv, json
outputFile = open('Docs/D2_05.csv', 'w', newline='')
outputWriter = csv.writer(outputFile)
outputWriter.writerow([city, dtime, w_main, w_desc])
outputFile.close()
http://api.openweathermap.org/data/2.5/forecast?q={city}&units=metric&APPID={APPID}
import csv, json, requests, datetime
def Forecast30hrs(location, csvfile, APPID):
# Use openweathermap API get json sting
url = 'http://api.openweathermap.org/data/2.5/forecast?q=%s&units=metric&APPID=%s' %(location, APPID)
response = requests.get(url)
response.raise_for_status()
# load json as dict()
weatherData = json.loads(response.text)
# Get weather information by the key of dict()
w = weatherData['list']
# Open csv file
path = 'Docs/'+ csvfile
outputFile = open(path, 'w', newline='')
outputWriter = csv.writer(outputFile)
# Write column names
outputWriter.writerow(['Forecast datetime', 'Temp. Range (Celsius)', \
'Group of weather parameters', 'Weather condition within the group'])
for i in range(10):
# Get Forecast datetime, min/max daily temperature, main, description
dtime = datetime.datetime.fromtimestamp(w[i]['dt']).strftime('%Y-%m-%d %H:%M:%S')
temp_min = w[i]['main']['temp_min']
temp_max = w[i]['main']['temp_max']
main = w[i]['weather'][0]['main']
desc = w[i]['weather'][0]['description']
# Write rows into csv file
outputWriter.writerow([dtime, str(temp_min)+ ' - ' +str(temp_max), main, desc])
outputFile.close()
APPID = '848b6cd4XXXXXXXXXXXXXXX'
Forecast30hrs('Taipei', 'D2_Exercise.csv', APPID)