使用檔案時,一種常見的問題是找不到檔案:你要查詢的檔案可能在其他地方、檔名可能不正確或者這個檔案根本就不存在。對於所有這些情形,都可使用try-except**塊以直觀的方式進行處理 。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @date : 2020-11-12 15:58:46
# @author : ericray
# @email : [email protected]
# @link :
# @description 統計字元及丟擲異常
defcount_words
(filename)
:try
:with
open
(filename)
as file_object:
contents = file_object.read(
)except filenotfounderror:
msg =
"sorry, the file "
+ filename +
" does not exist."
print
(msg)
else
: words = contents.split(
) num_words =
len(words)
print
("the file "
+ filename +
" has about "
+str
(num_words)
+" words."
)"""
try**塊引發filenotfounderror異常,因此python找出與該錯誤匹配的
except**塊,並執行其中的**。最終的結果是顯示一條友好的錯誤訊息,而不是traceback
"""filename =
'alice.txt'
count_words(filename)
filenames =
['alice.txt'
,'siddhartha.txt'
,'moby_dick.txt'
,'little_women.txt'
]for filename in filenames:
count_words(filename)
# 本示例中 little_women.txt檔案不存在
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @date : 2020-11-13 09:44:43
# @author : ericray
# @email : [email protected]
# @link :
# @description :迴圈輸入兩個數字,判斷是否為數字,並丟擲異常
print
("please give me two number, and i'll add them."
)print
("enter 'q' to quit."
)while
true
: first_number =
input
("\nfirst number:"
)if first_number ==
'q':
break
second_number =
input
("\nsecond number:"
)if second_number ==
'q':
break
try:
answer =
int(first_number)
+int
(second_number)
except valueerror:
print
("the input must be number,please check them!"
)else
:print
("the sum of "
+str
(first_number)
+" and "
+str
(second_number)
+" is "
+str
(answer)
)
python檔案相關操作參考:python檔案讀寫基本用法 python之檔案讀寫和異常處理
檔案讀取 寫入和異常處理操作舉例 date 2017 07 17 file name d file demo.txt with open file name,w as write file obj 寫入檔案 write file obj.write hello n write file obj.wr...
python之檔案讀寫和異常處理
檔案讀取 寫入和異常處理操作舉例 date 2017 07 17 file name d file demo.txt with open file name,w as write file obj 寫入檔案 write file obj.write hello n write file obj.wr...
python檔案讀寫 異常處理
函式open 檔案讀寫,預設讀模式 open 路徑檔名.字尾名 eg file open d tes.txt content file.read print content file.close 讀 read 從文件開始位置讀取 readline 讀取一行內容,檔案指標在 就從 開始讀取一行 rea...