1. 程式人生 > >Python筆記(五):異常處理和數據存儲

Python筆記(五):異常處理和數據存儲

utf-8 load 模塊 修改 val 麻煩 數據存儲 poke 關閉

註:和上一篇有關聯

(一) finally 和 輸出異常信息

try:
the_man = open(r‘C:\Users\123456\Desktop\test.txt‘)
print(the_man.readline(),end="")
except IOError as err:
#輸出異常信息
print("異常信息:"+ str(err))
#str()轉換為字符串
finally:
#不管是否發生異常一定會執行
the_man.close()

(二) 使用 with

(1) 上面的代碼如果文件不存在,就不會創建the_man對象,那麽執行the_man.close()就會出現NameError錯誤,所以得先判斷是否存在文件 test.txt是否存在

try:
the_man = open(‘test.txt‘)
print(the_man.readline(),end="")
except IOError as err:
#輸出異常信息
print("異常信息:"+ str(err))
finally:
#不管是否發生異常一定會執行
if ‘test.txt‘ in os.listdir():
#判斷當前工作目錄是否存在 test.txt 文件,存在時才關閉文件
the_man.close()

(2) 用(1)中的比較麻煩,可以使用with替代,下面的代碼等價上面的代碼。使用with時,PYTHON會自動去關閉文件。

try:
with open(‘test.txt‘) as the_man:
print(the_man.readline(),end="")
except IOError as err:
#輸出異常信息
print("異常信息:"+ str(err))

(三) 通過open(),將數據寫入文件。

man = [1,2,3]
try:
with open(‘test.txt‘,‘w‘) as the_man:
print(man,file=the_man)
#man是要寫入的數據, file= 是要寫入的文件對象
except IOError as err:
#輸出異常信息
print("異常信息:"+ str(err))

(四) 將數據長期存儲

通過pickle 實現,代碼如下。
import pickle
man = [1,2,3]
with open(‘the_man.pickle‘,‘wb‘) as saveman:
pickle.dump(man,saveman)
#保存數據
with open(‘the_man.pickle‘,‘rb‘) as resman:
man = pickle.load(resman)
#需要時恢復數據
print(man)

(五) 接上篇(筆記4),判斷話是張三還是李四說的,分別添加到不同的列表,並存儲到zs.txt和ls.txt中。

(1) 處理文件代碼

from FirstPython import the_list as tl
#導入the_list模塊
zs = []
ls = []
ww = []
try:
with open(r‘C:\Users\123456\Desktop\測試.txt‘,encoding=‘UTF-8‘) as the_file:
for each_line in the_file:
try:
(role,line_spoken) = each_line.split(":",1)
if role ==張三‘:
# 如果role==張三,將line_spoken添加到man列表
zs.append(line_spoken)
elif role ==李四‘:
ls.append(line_spoken)
elif role == 王五‘:
ww.append(line_spoken)
except ValueError:
# 出現ValueError時,直接輸出 each_line的值
print(each_line,end="")
the_file.close()
except IOError:
#找不到文件時提示文件不存在
print("文件不存在!")
try:
with open(r‘C:\Users\123456\Desktop\zs.txt‘,‘w‘) as the_man:
tl.dslist(zs,the_man)
#調用dslist方法處理列表數據
with open(r‘C:\Users\123456\Desktop\ls.txt‘,‘w‘) as the_other:
tl.dslist(ls,the_other)
# 調用dslist方法處理列表數據
except IOError:
print("文件不存在!")

(2) 處理列表數據的函數,模塊名:the_list(Python筆記(二)中做過說明,這裏做了一點修改)

def dslist(the_list,the_file):
#the_list:要處理的列表數據
#the_file:要寫入的文件對象
for each_line in the_list:
if isinstance(each_line,list):
#數據類型是否為列表
dslist(each_line,the_file)
else:
print(each_line,file=the_file,end="")

Python筆記(五):異常處理和數據存儲