## wk15_1214_檔案與例外處理_line貼圖收集器 黃冠維 9.1 檔案的操作 <pre> 開啟檔案的語法 開啟檔案的模式 使用with...as 語法 檔案處理 </pre> 9.2 檔案和目錄管理 <pre> os.path 模組 os 模組 </pre> 9.3 例外處理 <pre> try...except...else...finally 語法 try...except...else...finally 使用方法 try...except 常用錯誤表 </pre> ## [inclass practice] ### {綜合演練} 實作1 : <pre>小智以readlines()函式讀取文字檔<in_a.txt>,計算出每一列的字元數(包括結束字元),並在每一列前面顯示</pre> 實作5: <pre> 阿吉得到大福真傳後很高興的執行前例自己完成的程式,但他發現當輸入正整數12可正確執行,可以顯示1、2、...、12,但輸入正數12.5後,程式又會出錯並且中斷執。 他想了很久還是不解,明明是輸入正數數值,為何會出現錯誤,於是又求救於大福,大福教他已except Exception as e 捕捉錯誤的資訊。 </pre> ### {範例} 1. 以讀取模式開啟檔案並顯示資料 <fileread1> 2. 以with...as語法開啟檔案並顯示資料 <fileread2> 3. 在每段文章的前面加上編號 <Addlineno> 4. 輸入兩個正整數求和,捕捉輸入的錯誤 <tryadd> 5. 捕捉飛數值資料和除數為0的錯誤 <trymod> ## [afterclass practice] 1. 以open(filename[,mode][,encode]) 開啟檔案,下列何者是 mode 參數預設的模式? (A) 讀取模式 (B) 寫入模式 (C) 附加模式 (D)以上皆是 Answer : (A) 2. Python 提供何種內建函式,可以開啟指定的檔案,以便進行檔案內容的讀取、寫入或修改? (A) file() (B) input() (C) open() (D) output() Answer : (C) 3. 下列何函式可以讀取一列字元? (A) readable() (B) read() (C) readlines() (D)get(ch) Answer : (B) 4. 下列程式建立的檔案物件,可以執行何種動作? f=open('file1.txt','w') f.write("Hello Python!") f.close() (A) 讀取 (B) 寫入 (C) 可讀取也可寫入 (D) 以上皆非 ```python f=open('file1.txt','w') f.write("Hello Python!") f.close() ``` Answer : (B) 5. 執行下列程式,下列顯示結果何者正確? try: print(x) except: print("y") finally: print("z") (A) x (B) y (C) xz (D) yz ```python try: print(x) except: print("y") finally: print("z") ``` y z Answer : (D) 6. open(filename,mode,encode) 函式的參數中,其中只有那一個參數是必填? (A) filename (B) mode (C) encode (D) 以上皆是 Answer : (A) 7. 如果作業系統是繁體中文 Windows 系統,預設的編碼為何? (A) UTF-8 (B) cp950 (C) unicode (D) GB2312 Answer : (B) 8. 下列有關 readlines() 的敘述,何者正確? (A) 會讀取全部文件內容 (B) 以串列方式傳回 (C) 包括「\n」跳列字元,甚至是隱含的字元 (D) 以上皆是 Answer : (D) 9. 執行下列程式,下列顯示結果何者正確? n=1 try: print(n) except: print("變數不存在!") (A) 1 (B) n (C) 變數不存在 (D) 以上皆是 ```python n=1 try: print(n) except: print("變數不存在!") ``` 1 Answer : (A) 10. 班上的除錯高手大匹,在他的程式中加入了錯誤的補捉在 try…except…finally 敘述中,無論例外有沒有發生都會執行下列那些程式區塊? (A) try (B) except (C) finally (D) 以上皆是 Answer : (C)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up