1.編寫程式,將包含學生成績的字典儲存為二進位制檔案,然後再讀取內容並顯示。
import pickle
keys = ['湘玉', '老白', '芙蓉', '秀才']
values = [90, 85, 89, 92]
dictionary = dict(zip(keys, values))
print(dictionary)
with open('score.dat','wb') as f:
try:
pickle.dump(dictionary, f)
f.close()
except:
print('寫檔案異常!')
with open('score.dat','rb') as f:
x = pickle.load(f)
f.close()
print(x)
#或者f=open('score.dat','wb')
pickle.dump(1,f)
pickle.dump(dictionary,f)
f.close
f=open('score.dat','rb')
pickle.load(f)
dictionary=pickle.load(f)
f.close()
print(dictionary)
執行效果:
2.異常和錯誤的區別:
語法錯誤和邏輯錯誤不屬於異常,但有些語法錯誤往往會導致異常,
例如由於大小寫拼寫錯誤而訪問不存在的物件。異常是指因為程式
出錯而在正常控制流以外採取的行為。當python檢測到乙個錯誤時,
直譯器就會指出當前流已無法繼續執行下去,這時候就出現了異常。
Python 二進位制檔案讀取
其實對於檔案單純的讀取還是非常好解決的。只要使用如下語句即可把檔案讀取出到變數temp中 如果對open函式的引數mode不熟悉,可以查閱 此處我們需要以二進位制方式讀取該檔案,因此mode rb with open filename,mode rb as file temp file.read f...
Python 二進位制檔案讀取顯示
filename raw input enter file name f open filename,rb f.seek 0,0 index 0 for i in range 0,16 print 3s hex i print for i in range 0,16 print 3s print w...
Python 二進位制檔案讀取顯示
python view plain copy filename raw input enter file name f open filename,rb f.seek 0,0 index 0 fori inrange 0,16 print 3s hex i print fori inrange 0,...