1.文件操作
a.基本過程:打開文件 -操作 -關閉文件
b.open(路勁沦偎,打開方式摸吠,encoding = 編碼方式)
c.設置編碼:utf -8 ,gbk
注意:如果是以二進制的形式打開文件(rb/br,wb/bw),不能設置編碼方式
with open() as 變量名:
文件操作
'''
文件打開操作完成后,會自動關閉文件
'''
2.Json
json是有特定格式的一種文本形式寡润,它有自己的語法
json文件就是后綴是.json的文本文件。
1.json格式對應的數(shù)據(jù)類型及其表現(xiàn)
1.1一個json文件只能存一個數(shù)據(jù)舅柜,這個數(shù)據(jù)的類型必須是以下類型中的一個梭纹。
'''
類型 格式 意義
a.對象(object) {"a":1,"b":[1,2]} 相當于字典
b.數(shù)組(array) [100,"a",true] 相當于list
c.數(shù)字(number) 100 包含整數(shù)和小數(shù)
d.字符串(string) ''abc'' 就是字符串
e.布爾 true/false 是/否
f.null : null(None) 空值
'''
import json
'''
一:json轉(zhuǎn)python數(shù)據(jù)
1.load(json文件對象):以json的格式致份,獲取文件中的內(nèi)容变抽。將內(nèi)容轉(zhuǎn)換成相應的python數(shù)據(jù)。
2.loads(json格式內(nèi)容的字符串,編碼方式):將json格式的內(nèi)容绍载,轉(zhuǎn)換成python對應的數(shù)據(jù)太伊。
'''
二:python轉(zhuǎn)json數(shù)據(jù)
'''
1.dump(需要寫入json文件中的python數(shù)據(jù),json文件對象)
2.dumps(需要轉(zhuǎn)換成json格式字符串的python數(shù)據(jù))
'''
3.python對json文件的支持
json ---> python
對象 ---> 字典
數(shù)組 ---> 列表
數(shù)字 ---> 整數(shù)逛钻、浮點數(shù)
true,false ---> 布爾(True锰提,F(xiàn)alse)
null ---> None
'''
python---> json
字典-----------------> 對象
列表,數(shù)組 -----------> 數(shù)組
整數(shù)曙痘、浮點數(shù) ---------> 數(shù)字
布爾(True,F(xiàn)alse)---> true立肘,false
None---------------> null
'''
4.異常捕獲
a.程序出現(xiàn)某種異常边坤,但是不想因為這個異常而讓程序崩潰。這個時候就可以使用異常捕獲機制
b.捕獲異常
1.形式一(捕獲所有異常)
try:
需要捕獲異常的代碼塊(可能會出現(xiàn)異常的代碼塊)
except:
出現(xiàn)異常后執(zhí)行的代碼
'''
執(zhí)行過程:依次執(zhí)行try后面的代碼塊谅年,一旦遇到異常茧痒,就馬上執(zhí)行except后面的代碼塊融蹂。執(zhí)行完后再執(zhí)行其他的代碼旺订。
如果try里面的代碼塊沒有異常,就不執(zhí)行except后面的代碼超燃,而執(zhí)行其他的代碼区拳。
'''
a = [1,2,3,5]
try:
print(a[5])
except:
print('捕獲到異常')
2.形式二
try:
需要捕獲異常的代碼塊(可能會出現(xiàn)異常的代碼塊)
except 錯誤類型:
出現(xiàn)異常后執(zhí)行的代碼
'''
執(zhí)行過程:依次執(zhí)行try后面的代碼塊,一旦遇到指定的異常意乓,就馬上執(zhí)行except后面的代碼塊樱调。執(zhí)行完后再執(zhí)行其他的代碼。
如果try里面的代碼塊沒有指定的異常届良,就不執(zhí)行except后面的代碼笆凌,而執(zhí)行其他的代碼
'''
a = [1,2,3,5]
try:
print(a[5])
except IndexError:
print('捕獲到異常')
a = [1,2,3,5]
try:
print(a[5])
except (IndexError,KeyError):
print('捕獲到異常')
3.形式三
try:
需要捕獲的異常的代碼塊(可能會出現(xiàn)異常的代碼塊)
except 錯誤類型1:
執(zhí)行語句1
except 錯誤類型2:
執(zhí)行語句2
'''
還是只會捕獲到一個異常
'''
4.形式四
try:
需要捕獲的異常的代碼塊(可能會出現(xiàn)異常的代碼塊)
except 錯誤類型1:
執(zhí)行語句1
except 錯誤類型2:
執(zhí)行語句2
finally:
執(zhí)行語句
'''
finally:不管有沒有異常,都會執(zhí)行finally里面的的東西士葫。
'''
def user_input():
try:
numb1 = float(input('請輸入除數(shù):'))
numb2 = float(input('請輸入被除數(shù):'))
except ValueError:
print('輸入類型錯誤乞而,請輸入數(shù)字!为障!')
user_input()
test(numb1,numb2)
def test(n,y):
try:
print('%f / %f = %.2f' % (n,y,n/y))
except ZeroDivisionError:
print('被除數(shù)不能為0')
user_input()
finally:
print('哈哈哈哈哈哈')
user_input()
作業(yè)
- 提取data.json中的數(shù)據(jù)晦闰,將每條數(shù)據(jù)中的name、text鳍怨、love和comment信息呻右。并且保存到另外一個json文件中 。
import json
info = []
with open('./data.json',encoding='utf-8') as f:
str1 = json.load(f)
for x in str1['data']:
dict1 = {'name':x['name'],'text':x['text'],'love':x['love'],'comment':x['comment']}
info.append(dict1)
with open('./data_test.json','w',encoding='utf-8') as f:
json.dump(info,f)
data_test.png
- 統(tǒng)計data.json中comment數(shù)量超過1000的個數(shù)
import json
with open('./data.json',encoding='utf-8') as f:
str1 = json.load(f)
count = 0
for info in str1['data']:
if int(info['comment']) > 1000:
count += 1
print(count)
'''
0
'''
- 將data.json文件中所有點贊數(shù)(love)對應的值超出1000的用k來表示鞋喇,例如1000修改為1k, 1345修改為1.3k
import json
with open('./data.json',encoding='utf-8') as f:
str1 = json.load(f)
update_info = {"code": 200,"data":[]}
for love_test in str1['data']:
if int(love_test['love']) > 1000:
love_num ='%.1fk'% (int(love_test['love']) / 1000)
love_test['love'] = str(love_num)
update_info['data'].append(love_test)
else:
update_info['data'].append(love_test)
with open('./new_data.json','w',encoding='utf-8') as f:
json.dump(update_info,f)
lave_count.png
- 寫猜數(shù)字游戲声滥,如果輸入有誤,提示重新輸入,直達輸入正確為止落塑。比如:輸入數(shù)字的時候沒有按要求輸入纽疟,提示重新輸入
import random
numb = random.randint(1,100)
while True:
try:
user_input = int(input('請輸入數(shù)字:'))
except:
continue
if user_input > numb:
print('大了')
elif user_input < numb:
print('小了')
else:
print('OK')
break
'''
請輸入數(shù)字:50
小了
請輸入數(shù)字:70
小了
請輸入數(shù)字:90
大了
請輸入數(shù)字:80
小了
請輸入數(shù)字:85
大了
請輸入數(shù)字:83
大了
請輸入數(shù)字:82
大了
請輸入數(shù)字:81
OK
'''
- 寫學生管理系統(tǒng)的添加學生功能(數(shù)據(jù)需要本地化),要求除了保存學生的基本信息以外還要保存學生的學號憾赁,但是學號需要自動生成污朽,生成原則:
添加第一個學生對應的學號是:py001
第二次添加的學生的學號是:py002
...
如果前面的學生因為各種原因被移除了,那后面添加學生的時候原則不變龙考,就是比如上次已經(jīng)添加到py012,那么前面不管有沒有刪除情況蟆肆,再次添加學生的學號是py013
import json
def add_student():
try:
user_name = input('請輸入你的名字:')
user_age = int(input('年紀:'))
user_sex = input('性別:')
except:
add_student()
stu = operation()
if len(stu['student_info']) == 0:
id = 0
else:
for x in stu['student_info']:
id = x['id']
stu_info ={'id':id+1,'name':user_name,'age':user_age,'sex':user_sex}
stu['student_info'].append(stu_info)
print(stu)
main_write(stu)
def operation():
try:
with open('./stu_system.json','r',encoding='utf-8') as f:
str1 = json.load(f)
return str1
except FileNotFoundError:
add_sys()
def add_sys():
with open('./stu_system.json', 'w', encoding='utf-8') as f1:
info = {"class":"python1806","student_info":[]}
json.dump(info,f1)
operation()
def main_write(stu):
with open('./stu_system.json','w',encoding='utf-8') as f:
json.dump(stu,f)
add_student()
'''
{"class": "python1806", "student_info": [{"id": 1, "name": "txf", "age": 11, "sex": "nan"}, {"id": 2, "name": "aa", "age": 11, "sex": "bb"}]}
'''