Python 檔案 和 異常處理
阿新 • • 發佈:2019-02-19
為什麼要用檔案
python的列表等資料結構很好用,然而這些程式碼中的資料都是耦合較高的。
時常需要用到外部資料,也就離不開檔案、資料庫...
怎麼使用檔案
關於檔案,python的基本輸入機制是基於行的。
open() BIF 用來開啟檔案。
close() BIF 用來關閉檔案。
檔案常用操作示例
sketch.py
程式碼段1#open the data file, and read the first two lines. data = open('sketch.txt') print(data.readline(),end = '') print(data.readline(),end = '') data.close()
程式碼段2
data = open('sketch.txt')
data.seek(0) #return to the head of the file.
for each_line in data:
if not each_line.find(':')==-1:
(role, word) = each_line.split(':',1)
print(role, end = '')
print(' said: ',end = '')
print(word, end ='')
data.close()
程式碼段3
#<handle exception,suggested method> try: data = open('sketch.txt') for each_line in data: try: (role, word) = each_line.split(':',1) print(role, end = '') print(' said: ',end = '') print(word, end ='') except ValueError: pass data.close() except IOError: print('The data file is missing!')
程式碼段1是讀入檔案並輸出前兩行的示例。
關於異常處理
後面兩段程式碼,主要用於處理一個不太特殊的“特殊情況”:非標準格式輸入造成的程式錯誤。
解決的方法 要麼給出額外的程式碼邏輯去處理,要麼通過異常處理方法解決。
前者的思路很清晰,每次做一件事前先判斷是否存在問題,但問題在於:
當需要解決的錯誤多了,程式碼很臃腫,程式碼本來的功能不突出。而且需要人工考慮各種各樣的錯誤,這本身往往並不可行。
後者允許錯誤發生,在錯誤發生時捕捉並進行處理。
兩種處理方法見程式碼段2、3。
備註:1.find(str)方法可以查詢str在目標字串中出現的位置下標, 如果沒有出現過該str,則返回-1.
2.split(mark)用於分割字串,和java的String.split()方法效果類似。
3.try/except類似與java的try/catch 程式碼段3針對檔案不存在,檔案行分割錯誤進行了異常處理。
進一步改進
以上程式碼需要進一步改進
1.如果發生了異常 關閉檔案語句不會被執行,這可能造成一系列嚴重問題->finally語句
2.還可以讓try/except更簡潔一點 ->with語句,自帶except功能
(稍後總結)
附:sketch.txt內容。
Man: Is this the right room for an argument?
Other Man: I've told you once.
Man: No you haven't!
Other Man: Yes I have.
Man: When?
Other Man: Just now.
Man: No you didn't!
Other Man: Yes I did!
Man: You didn't!
Other Man: I'm telling you, I did!
Man: You did not!
Other Man: Oh I'm sorry, is this a five minute argument, or the full half hour?
Man: Ah! (taking out his wallet and paying) Just the five minutes.
Other Man: Just the five minutes. Thank you.
Other Man: Anyway, I did.
Man: You most certainly did not!
Other Man: Now let's get one thing quite clear: I most definitely told you!
Man: Oh no you didn't!
Other Man: Oh yes I did!
Man: Oh no you didn't!
Other Man: Oh yes I did!
Man: Oh look, this isn't an argument!
(pause)
Other Man: Yes it is!
Man: No it isn't!
(pause)
Man: It's just contradiction!
Other Man: No it isn't!
Man: It IS!
Other Man: It is NOT!
Man: You just contradicted me!
Other Man: No I didn't!
Man: You DID!
Other Man: No no no!
Man: You did just then!
Other Man: Nonsense!
Man: (exasperated) Oh, this is futile!!
(pause)
Other Man: No it isn't!
Man: Yes it is!
本文參考Head First Python 第三章。