1.文件操作
補充:打開文件的時候是以讀的方式打開侵佃,如果文件不存在會報:FileNotFoundError
打開文件的時候是以寫的方式打開, 如果文件不存在會自動創(chuàng)建對應的文件
0.打開文件和關(guān)閉文件的縮寫
with open(文件路徑, 打開方式, encoding=編碼方式) as 文件對象:
文件操作相關(guān)的代碼
說明:打開文件,執(zhí)行完文件操作相關(guān)的代碼后姐扮,會自動關(guān)閉本打開的這個文件
with open('./files/aaa.txt', 'w', encoding='utf-8') as f1:
f1.write('床前明月光,\n 疑是地上霜\n')
1.二進制文件的讀和寫
常見的二進制文件: 視頻文件拓颓、音頻文件语婴、圖片、壓縮包等都是屬于二進制文件
bytes --> 字節(jié)驶睦,是python專門用來表示二進制的數(shù)據(jù)類型
注意:二進制文件不能設置文件編碼方式(不能給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)
2.json文件
json是一種特定格式的數(shù)據(jù)砰左,主要用來在互聯(lián)網(wǎng)上做文本數(shù)據(jù)傳輸。
json數(shù)據(jù)本身是文本數(shù)據(jù)场航;json文件就是后綴是.json的文件, 并且文件內(nèi)容必須滿足json格式的要求
1.json格式
a.一個json對應一條數(shù)據(jù)
b.json中的數(shù)據(jù)必須是json對應的數(shù)據(jù)類型
數(shù)字類型(number) --> 所有的數(shù)字缠导,包含整數(shù)和小數(shù),例如:100, 12.5
字符串類型(string) --> 用雙引號括其的數(shù)據(jù)溉痢,例如:"abc", "你好僻造,世界!"
數(shù)組(array) --> 相當于python中列表, 例如: [100, 230, "abc", "你好"]
字典(dictionary) --> 相當于python中的字典, 例如:{"a": 100, "b":[1, 2, 3, 4, 5], "c":{}}
布爾 ---> true和false
null --> 相當于None, 用來表示空
2.python對json的支持
python中專門提供了一個json模塊孩饼,用來處理json數(shù)據(jù)
load(json文件對象) ---> 將json文件的內(nèi)容讀出來髓削,并且將內(nèi)容轉(zhuǎn)換成python對應的數(shù)據(jù)類型
dump(內(nèi)容, json文件路徑) --> 將指定的內(nèi)容,以json格式寫入到指定的json文件中
loads(json格式字符串) --> 將字符串內(nèi)容是json數(shù)據(jù)的字符串轉(zhuǎn)換成python對應的數(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(文件對象) --> 將文件對象中的內(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 字符串(會將單引號變成雙引號)
True/False true/false
dict 字典
列表/元祖 數(shù)組
None null
注意:除了上面列出的類型,其他類型不能直接轉(zhuǎn)換成json格式的數(shù)據(jù)
3.dumps
dumps(內(nèi)容) --> 內(nèi)容是python數(shù)據(jù)梯码。返回值是一個字符串宝泵,并且字符串的內(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)容, 文件對象) --> 將內(nèi)容以json格式寫入文件中
with open('./files/test3.json', 'w') as f:
json.dump({'a': 100, 'b':200, 'c': True}, f)
3.異常捕獲
raise 異常類型
異常類型要求:是Exception類的子類
value = int(input('請輸入一個偶數(shù):'))
if value & 1:
raise ValueError
else:
print('恭喜,還活著!')
1.報錯 --> 出現(xiàn)異常(后面的代碼不會執(zhí)行轩娶,并且程序會直接結(jié)束)
2.異常捕獲
出現(xiàn)異常儿奶,不希望程序直接崩潰,而是想要自己對這個異常進行處理鳄抒,就需要捕獲異常
格式1(可以捕獲代碼段1中出現(xiàn)的所有類型的異常):
try:
代碼段1
except:
代碼段2
finally:
代碼段3
說明:執(zhí)行代碼段1并且檢測代碼段1是否發(fā)生異常闯捎,如果發(fā)生異常程序不崩潰而是直接執(zhí)行代碼段2
try:
value = input('請輸入數(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后的括號中所有的異常
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('下標越界')
except KeyError:
print('key不存在')
finally后面的代碼段一定會執(zhí)行(不管try里面的代碼時候會出現(xiàn)異常许溅,以及出現(xiàn)異常后異常是否被捕獲)
(寫遺書瓤鼻!)
try:
f = open('./files/aaa.txt')
except IndexError:
print('文件不存在!')
finally:
print('最后會執(zhí)行的代碼')