Python文件_捕獲異常


捕獲異常

1.讀寫文件的時候有很多容易出錯的地方;如果你要打開的文件不存在,就會得到一個IOerror:

>>> find = open('bad_file.txt')

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

FileNotFoundError: [Errno 2] No such file or directory: 'bad_file.txt'

2.如果你要讀取一個文件卻沒有權限,就得到一個權限錯誤permissionError:

>>> fout = open('/etc/passwd', 'w')

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

PermissionError: [Errno 1] Operation not permitted: '/etc/passwd'

3.如果你把一個目錄錯當做文件來打開,就會得到下面這種IsADirectoryError錯誤了:

>>> find = open('/home')

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

IsADirectoryError: [Errno 21] Is a directory: '/home'

我們可以用像是os.path.exists、os.path.isfile 等等這類的函數來避免上面這些錯誤,不過這就需要很長時間,

還要檢查很多代碼(比如“IsADirectoryError: [Errno 21] Is a directory: '/home'”,這里的[Errno 21]就表明有至少21處地方有可能存在錯誤)。

所以更好的辦法是提前檢查,用 try 語句來實現,這種語句就是用來處理異常情況的。其語法形式就跟 if...else 語句是差不多的:

>>> try:

...    fout = open('bad_file.txt')

... except:

...    print('something went wrong!')

... 

something went wrong!

過程:

Python 會先執行 try 后面的語句。如果運行正常,就會跳過 except 語句,然后繼續運行。如果發生異常,就會跳出 try 語句,然后運行 except 語句中的代碼。

這種用 try 語句來處理異常的方法,就叫文件的異常捕獲。上面的例子中,except 語句中的輸出信息並沒有實質性作用,僅僅是檢查是否執行語句,而后的返回。

結束。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM