01-文件操作
補(bǔ)充:打開文件的時(shí)候是以讀的方式打開,如果文件不存在會(huì)報(bào):FileNotFoundError
打開文件的時(shí)候是以寫的方式打開, 如果文件不存在會(huì)自動(dòng)創(chuàng)建對(duì)應(yīng)的文件
0.打開文件和關(guān)閉文件的縮寫
with open(文件路徑, 打開方式, encoding=編碼方式) as 文件對(duì)象:
文件操作相關(guān)的代碼
說明:打開文件,執(zhí)行完文件操作相關(guān)的代碼后,會(huì)自動(dòng)關(guān)閉本打開的這個(gè)文件
with open('./files/aaa.txt', 'w', encoding='utf-8') as f1:
f1.write('床前明月光,\n 疑是地上霜\n')
1.二進(jìn)制文件的讀和寫
常見的二進(jìn)制文件: 視頻文件、音頻文件、圖片、壓縮包等都是屬于二進(jìn)制文件
bytes --> 字節(jié),是python專門用來表示二進(jìn)制的數(shù)據(jù)類型
注意:二進(jìn)制文件不能設(shè)置文件編碼方式(不能給encoding賦值)
with open('./files/luffy4.jpg', 'rb') as f2:
content = f2.read()
print(type(content), content)
with open('./files/new.jpg', 'wb') as f2:
f2.write(content)
02-json文件
json是一種特定格式的數(shù)據(jù),主要用來在互聯(lián)網(wǎng)上做文本數(shù)據(jù)傳輸。
json數(shù)據(jù)本身是文本數(shù)據(jù);json文件就是后綴是.json的文件, 并且文件內(nèi)容必須滿足json格式的要求
1.json格式
a.一個(gè)json對(duì)應(yīng)一條數(shù)據(jù)
b.json中的數(shù)據(jù)必須是json對(duì)應(yīng)的數(shù)據(jù)類型
數(shù)字類型(number) --> 所有的數(shù)字,包含整數(shù)和小數(shù),例如:100, 12.5
字符串類型(string) --> 用雙引號(hào)括其的數(shù)據(jù),例如:"abc", "你好,世界!"
數(shù)組(array) --> 相當(dāng)于python中列表, 例如: [100, 230, "abc", "你好"]
字典(dictionary) --> 相當(dāng)于python中的字典, 例如:{"a": 100, "b":[1, 2, 3, 4, 5], "c":{}}
布爾 ---> true和false
null --> 相當(dāng)于None, 用來表示空
2.python對(duì)json的支持
python中專門提供了一個(gè)json模塊,用來處理json數(shù)據(jù)
load(json文件對(duì)象) ---> 將json文件的內(nèi)容讀出來,并且將內(nèi)容轉(zhuǎn)換成python對(duì)應(yīng)的數(shù)據(jù)類型
dump(內(nèi)容, json文件路徑) --> 將指定的內(nèi)容,以json格式寫入到指定的json文件中
loads(json格式字符串) --> 將字符串內(nèi)容是json數(shù)據(jù)的字符串轉(zhuǎn)換成python對(duì)應(yīng)的數(shù)據(jù)類型數(shù)據(jù)
dumps(內(nèi)容) --> 將指定的內(nèi)容,轉(zhuǎn)換成json格式的字符串
json轉(zhuǎn)換python:
json python
數(shù)字 int/float
字符串 str
數(shù)組 list
字典 dict
true/false True/False
null None
"""
import json
1.loads
loads(字符串) --> 要求字符串的內(nèi)容必須滿足json格式
content = json.loads('100.12')
print(content, type(content))
content = json.loads('"abc"')
print(content, type(content))
content = json.loads('[12, 12.8, "name", [1, "2a"]]')
print(content, type(content))
print(type(content[3]))
content = json.loads('{"a": 100, "b": true, "c": false, "d": null}')
print(content, type(content))
2.load
load(文件對(duì)象) --> 將文件對(duì)象中的內(nèi)容轉(zhuǎn)換成python數(shù)據(jù)類型數(shù)據(jù)。要求文件中的內(nèi)容必須是json格式的數(shù)據(jù)
with open('./files/test.txt') as f:
print(json.load(f))
python轉(zhuǎn)json:
python json
int/float 數(shù)字
str 字符串(會(huì)將單引號(hào)變成雙引號(hào))
True/False true/false
dict 字典
列表/元祖 數(shù)組
None null
注意:除了上面列出的類型,其他類型不能直接轉(zhuǎn)換成json格式的數(shù)據(jù)
3.dumps
dumps(內(nèi)容) --> 內(nèi)容是python數(shù)據(jù)。返回值是一個(gè)字符串,并且字符串的內(nèi)容滿足是json格式的
str1 = json.dumps([1, 2, 'abc'])
print(str1)
print(json.dumps((100, 200, 'abc')))
str1 = json.dumps({'a': -12.34, 'b': True, 'c': 'Hello'})
print(str1, type(str1))
4.dump
dump(內(nèi)容, 文件對(duì)象) --> 將內(nèi)容以json格式寫入文件中
with open('./files/test3.json', 'w') as f:
json.dump({'a': 100, 'b':200, 'c': True}, f)
03-文件的使用
數(shù)據(jù)本地化的過程:使用數(shù)據(jù)的時(shí)候從本地文件中去取數(shù)據(jù);修改完數(shù)據(jù)后要使用新的數(shù)據(jù)去更新本地文件中的內(nèi)容
學(xué)生管理系統(tǒng)
1.添加學(xué)生,要求之前添加過的學(xué)生,下次執(zhí)行程序的時(shí)候還存在
2.顯示學(xué)生信息
學(xué)生管理數(shù)據(jù)類型 --> [學(xué)生1, 學(xué)生2], {'學(xué)號(hào)1':學(xué)生1, '學(xué)號(hào)2':學(xué)生2}
import json
# 保存所有的學(xué)生
with open('./files/students.json') as f:
all_student = json.load(f)
def add_student():
"""
添加學(xué)生
"""
while True:
name = input('請(qǐng)輸入學(xué)生的姓名:')
age = input('請(qǐng)輸入學(xué)生的年齡:')
tel = input('請(qǐng)輸入學(xué)生的電弧:')
# 創(chuàng)建學(xué)生對(duì)應(yīng)的字典
student = {'name': name, 'age': age, 'tel': tel}
# 將學(xué)生添加到容器中
all_student.append(student)
# 將新的數(shù)據(jù)更新到本地文件中
with open('./files/students.json', 'w') as f:
json.dump(all_student, f)
print('添加成功!')
print('1.繼續(xù)添加')
print('2.返回上一層')
input_value = input('請(qǐng)選擇(1-2):')
if input_value == '1':
continue
else:
return
def show_student():
for student in all_student:
print(student)
# while True:
# print('======================')
# print('1.添加學(xué)生')
# print('2.顯示學(xué)生信息')
# print('3.退出')
# print('======================')
# input_value = input('請(qǐng)選擇(1-3):')
# if input_value == '1':
# add_student()
# elif input_value == '2':
# show_student()
# else:
# print('退出成功!')
# break
1.在程序中聲明一個(gè)變量用來保存當(dāng)前程序執(zhí)行的次數(shù)
with open('./files/test2.json') as f:
num = json.load(f)
num += 1
with open('./files/test2.json', 'w') as f:
json.dump(num, f)
print(num)
04-異常捕獲
===============拋出異常=============
raise 異常類型
異常類型要求:是Exception類的子類
value = int(input('請(qǐng)輸入一個(gè)偶數(shù):'))
if value & 1:
raise ValueError
else:
print('恭喜,還活著!')
===============異常捕獲=============
1.報(bào)錯(cuò) --> 出現(xiàn)異常(后面的代碼不會(huì)執(zhí)行,并且程序會(huì)直接結(jié)束)
print('========')
a = 10 + 'abc'
print('!!!!')
2.異常捕獲
出現(xiàn)異常,不希望程序直接崩潰,而是想要自己對(duì)這個(gè)異常進(jìn)行處理,就需要捕獲異常
格式1(可以捕獲代碼段1中出現(xiàn)的所有類型的異常):
try:
代碼段1
except:
代碼段2
finally:
代碼段3
說明:執(zhí)行代碼段1并且檢測(cè)代碼段1是否發(fā)生異常,如果發(fā)生異常程序不崩潰而是直接執(zhí)行代碼段2
try:
value = input('請(qǐng)輸入數(shù)字:')
int_value = float(value)
except:
print('出現(xiàn)了異常')
print('輸入有誤!')
try:
b = {'a': 10}['aa']
index = 1
a = [1, 2, 3][index]
print('~~~~~~')
except:
print('又出現(xiàn)異常了!')
格式2:
try:
代碼段1
except 異常類型:
代碼段2
finally:
代碼段3
說明: 捕獲代碼段1中出現(xiàn)的指定類型的異常。
try:
# print({'a': 100}['b'])
print([1, 2][3])
except IndexError:
print('出現(xiàn)異常2')
格式3:
try:
代碼段1
except (異常類型1,異常類型2,...):
代碼段2
finally:
代碼段3
說明:捕獲except后的括號(hào)中所有的異常
try:
print([1, 2][3])
print({'a': 'abc'}['b'])
except (IndexError, KeyError):
print('出現(xiàn)異常3')
格式4:
try:
代碼段1
except 異常類型1:
代碼段2
except 異常類型2:
代碼段3
finally:
代碼段4
try:
print({'a': 100}['b'])
print([1, 2][3])
except IndexError:
print('下標(biāo)越界')
except KeyError:
print('key不存在')
finally后面的代碼段一定會(huì)執(zhí)行(不管try里面的代碼時(shí)候會(huì)出現(xiàn)異常,以及出現(xiàn)異常后異常是否被捕獲)
(寫遺書!)
try:
f = open('./files/aaa.txt')
except IndexError:
print('文件不存在!')
finally:
print('最后會(huì)執(zhí)行的代碼')
print('======!')