文件和異常
文件和異常我再前面已經(jīng)搞了一波了慧域,這個(gè)是大神的順序,我把傳送門放這
大概放些概念和補(bǔ)充知識(shí)在下面
1. 文件
在實(shí)際開發(fā)中窿撬,常常需要對(duì)程序中的數(shù)據(jù)進(jìn)行持久化操作,而實(shí)現(xiàn)數(shù)據(jù)持久化最直接簡單的方式就是將數(shù)據(jù)保存到文件中展融。說到“文件”這個(gè)詞寞射,可能需要先科普一下關(guān)于文件系統(tǒng)的知識(shí)渔工,對(duì)于這個(gè)概念,維基百科上給出了很好的詮釋桥温,這里不再浪費(fèi)筆墨引矩。
2. 異常
為了讓代碼有一定的健壯性和容錯(cuò)性,我們可以使用Python的異常機(jī)制對(duì)可能在運(yùn)行時(shí)發(fā)生狀況的代碼進(jìn)行適當(dāng)?shù)奶幚砬纸赑ython中旺韭,我們可以將那些在運(yùn)行時(shí)可能會(huì)出現(xiàn)狀況的代碼放在try代碼塊中,在try代碼塊的后面可以跟上一個(gè)或多個(gè)except來捕獲可能出現(xiàn)的異常狀況掏觉。例如在上面讀取文件的過程中区端,文件找不到會(huì)引發(fā)FileNotFoundError,指定了未知的編碼會(huì)引發(fā)LookupError澳腹,而如果讀取文件時(shí)無法按指定方式解碼會(huì)引發(fā)UnicodeDecodeError织盼,我們?cè)趖ry后面跟上了三個(gè)except分別處理這三種不同的異常狀況。最后我們使用finally代碼塊來關(guān)閉打開的文件酱塔,釋放掉程序中獲取的外部資源沥邻,由于finally塊的代碼不論程序正常還是異常都會(huì)執(zhí)行到(甚至是調(diào)用了sys模塊的exit函數(shù)退出Python環(huán)境,finally塊都會(huì)被執(zhí)行羊娃,因?yàn)閑xit函數(shù)實(shí)質(zhì)上是引發(fā)了SystemExit異常)唐全,因此我們通常把finally塊稱為“總是執(zhí)行代碼塊”,它最適合用來做釋放外部資源的操作蕊玷。如果不愿意在finally代碼塊中關(guān)閉文件對(duì)象釋放資源邮利,也可以使用上下文語法,通過with關(guān)鍵字指定文件對(duì)象的上下文環(huán)境并在離開上下文環(huán)境時(shí)自動(dòng)釋放文件資源
詳細(xì)的看上面異常的傳送門
3. json
這是個(gè)好東東垃帅,大部分可見的配置呀延届,http的協(xié)議,基本上都是json協(xié)議挺智,所以這個(gè)是要學(xué)習(xí)一下:
json的字符串長這個(gè)樣子:
{
"name": "駱昊",
"age": 38,
"qq": 957658,
"friends": ["王大錘", "白元芳"],
"cars": [
{"brand": "BYD", "max_speed": 180},
{"brand": "Audi", "max_speed": 280},
{"brand": "Benz", "max_speed": 320}
]
}
可以通過在線網(wǎng)站校驗(yàn)json格式有沒有問題
傳送門
剛開始是這樣
正確的是這樣的
錯(cuò)誤的是這樣的
會(huì)有提示祷愉,照著改就是了
3.1 json 和python格式對(duì)應(yīng)關(guān)系
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number (int / real) | int / float |
true / false | True / False |
null | None |
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int- & float-derived Enums | number |
True / False | true / false |
None | null |
python
里有個(gè)json
模塊提供給我們用來json
格式華操作窗宦,
json
模塊主要有四個(gè)比較重要的函數(shù)赦颇,分別是:
-
dump
- 將Python對(duì)象按照J(rèn)SON格式序列化到文件中 -
dumps
- 將Python對(duì)象處理成JSON格式的字符串 -
load
- 將文件中的JSON數(shù)據(jù)反序列化成對(duì)象 -
loads
- 將字符串的內(nèi)容反序列化成Python對(duì)象
實(shí)際操作一波:
import json
dict = {
"name": "駱昊",
"age": 38,
"qq": 957658,
"friends": ["王大錘", "白元芳"],
"cars": [
{"brand": "BYD", "max_speed": 180},
{"brand": "Audi", "max_speed": 280},
{"brand": "Benz", "max_speed": 320}
]
}
dict2 = {
123:123
}
json_str = json.dumps(dict,ensure_ascii=False)
print(json_str)
load_str = json.loads(json_str)
print(load_str)
with open('json.txt','w',encoding='utf-8') as fjson:
json.dump(dict,fjson,ensure_ascii=False)
fjson.write('\n')
json.dump(dict2, fjson)
with open('json.txt','r',encoding='utf-8') as fjson_r:
for line in fjson_r:
print(line)
load_str = json.loads(line)
print('load_str',load_str)
結(jié)果:
E:\learn100day\venv\Scripts\python.exe E:/learn100day/day013_home.py
{"name": "駱昊", "age": 38, "qq": 957658, "friends": ["王大錘", "白元芳"], "cars": [{"brand": "BYD", "max_speed": 180}, {"brand": "Audi", "max_speed": 280}, {"brand": "Benz", "max_speed": 320}]}
{'name': '駱昊', 'age': 38, 'qq': 957658, 'friends': ['王大錘', '白元芳'], 'cars': [{'brand': 'BYD', 'max_speed': 180}, {'brand': 'Audi', 'max_speed': 280}, {'brand': 'Benz', 'max_speed': 320}]}
{"name": "駱昊", "age": 38, "qq": 957658, "friends": ["王大錘", "白元芳"], "cars": [{"brand": "BYD", "max_speed": 180}, {"brand": "Audi", "max_speed": 280}, {"brand": "Benz", "max_speed": 320}]}
load_str {'name': '駱昊', 'age': 38, 'qq': 957658, 'friends': ['王大錘', '白元芳'], 'cars': [{'brand': 'BYD', 'max_speed': 180}, {'brand': 'Audi', 'max_speed': 280}, {'brand': 'Benz', 'max_speed': 320}]}
{"123": 123}
load_str {'123': 123}
文件里:
搞這個(gè)東東,中英文赴涵,還有一個(gè)文件多個(gè)json的時(shí)候媒怯,得注意
3.2 http請(qǐng)求中使用到的json
這里找了個(gè)請(qǐng)求天氣的接口,返回的是json髓窜,千萬不要死循環(huán)請(qǐng)求扇苞,會(huì)被關(guān)在小黑屋子里的欺殿。。鳖敷。
請(qǐng)求http 用的requests模塊脖苏,接口的傳送門
直接上代碼,只能查詢城市的定踱,省的查不了棍潘,縣及其一下查不了。崖媚。亦歉。
import json
import requests
dict = {}
with open('city.json','r',encoding='utf-8') as fcity:
json_str = json.load(fcity)
for perjson in json_str:
# print(perjson)
dict[perjson['city_name']] = perjson['city_code']
# for key in dict.keys():
#print(key, ':', dict[key])
while True:
# inpuit_str = input('請(qǐng)輸入要查詢城市的天氣:')
inpuit_str = '北京'
city_str = str(inpuit_str)
if city_str in dict.keys():
pass
code_str = dict[city_str]
if code_str is '':
print('請(qǐng)輸入具體城市,不要輸入省份畅哑!')
else:
http_str = 'http://t.weather.sojson.com/api/weather/city/' + code_str
print(http_str)
resp = requests.get(http_str)
data_model = json.loads(resp.text)
# print(data_model)
json_data = data_model['data']
# print(json_data)
json_forecast = json_data['forecast']
print(city_str,'今天天氣:', json_forecast[0]['type'],', 風(fēng)向:',json_forecast[0]['fx'], ', 風(fēng)力:',
json_forecast[0]['fl'], '肴楷,溫度:', json_forecast[0]['high'], ',', json_forecast[0]['low'] )
exit(0)
else:
print('輸入有誤請(qǐng)重新輸入荠呐!')
請(qǐng)輸入要查詢城市的天氣:kunshan
輸入有誤請(qǐng)重新輸入赛蔫!
請(qǐng)輸入要查詢城市的天氣:昆山
輸入有誤請(qǐng)重新輸入!
請(qǐng)輸入要查詢城市的天氣:蘇州
http://t.weather.sojson.com/api/weather/city/101190401
蘇州 今天天氣: 多云 , 風(fēng)向: 西北風(fēng) , 風(fēng)力: <3級(jí) 直秆,溫度: 高溫 32.0℃ 濒募, 低溫 26.0℃
city.json 去這兒下載:鏈接: https://pan.baidu.com/s/1JFAwnH2MRLc5OD3hsJZwGQ 提取碼: u8sk
如果鏈接失效就去網(wǎng)站看看,不行就聯(lián)系我圾结。瑰剃。。下載之后名字改成city.json筝野,和python文件一個(gè)目錄就行
文集傳送門 學(xué)習(xí)python100天
整個(gè)學(xué)習(xí)python100天的目錄傳送門
無敵分割線
再最后面附上大神的鏈接
傳送門