python基礎語法速查速學 捕獲異常

2021-10-09 14:57:40 字數 1561 閱讀 5926

try

:print

("-----發生異常前-----"

) f =

open

("123.txt"

,"r"

)# 制度模式開啟乙個不存在的檔案會發生異常

print

("-----發生異常後-----"

)except ioerror:

# except後跟異常名

print

("發生了ioerror"

)

-----發生異常前-----

發生了ioerror

try

:print

("-----發生異常前-----"

) f =

open

("123.txt"

,"r"

)# 制度模式開啟乙個不存在的檔案會發生異常

print

("-----發生異常後-----"

)except

(nameerror,ioerror)

as result:

# except後跟異常名

print

("發生了錯誤"

)print

(result)

-----發生異常前-----

發生了錯誤

[errno 2] no such file or directory: '123.txt'

import time

try:

f =open

("test.txt"

,"r"

)#開啟檔案

try:

while

true

: content = f.readline(

)#一行行的讀取檔案

iflen

(content)==0

:#當讀取到的內容長度為0的時候說明讀取完了

break

#跳出迴圈

time.sleep(1)

#每次迴圈等1秒方便輸出

print

(content,end="")

#輸出每次讀到的一行的內容,結尾不換行

finally

:#最後一定會執行的

f.close(

)#關閉檔案

print

("檔案關閉"

)except exception as result:

print

("發生異常..."

)print

(result)

hello world!01

hello world!02

hello world!03

hello world!04

hello world!05檔案關閉

python基礎語法速查速學 字典

字典的定義 info 字典的訪問 print info name print info age 吳彥祖 18print info gender keyerror traceback most recent call last in 1 直接訪問,不存在的鍵會報錯 2 print info gende...

Python 基礎速查表

資料型別 integer 256,15 float 253.23,1.253e 10 string hel lo goodbye mul til ine boolean true,false list value,tuple value,dictionary set 語句if 語句 if expre...

10天Python基礎速學 第二天

基本資料型別 結束語python的語法 基本資料型別與c語言有很大的相似,若學過c語言基礎的話,在接下來的學習會很簡單,不過,沒學過c語言基礎也沒事,只需要接下來多加記憶就好。文章中加粗字型為重點,會經常使用到 接下來,我以hello world為例,給大家舉例python的輸出。在python中與...