### wk15_B1121138_邱冠誠 9.1 檔案的操作 開啟檔案的語法 開啟檔案的模式 使用with...as 語法 檔案處理 9.2 檔案和目錄管理 os.path 模組 os 模組 9.3 例外處理 try...except...else...finally 語法 try...except...else...finally 使用方法 try...except 常用錯誤表 【inclass practice】 ```python= ## 課本原始檔 import requests, json, os from bs4 import BeautifulSoup url = 'https://store.line.me/stickershop/product/8991459/zh-Hant' #人的日常 html = requests.get(url) sp = BeautifulSoup(html.text, 'html.parser') #datas = sp.find_all('li', {'class':'mdCMN09Li FnStickerPreviewItem'}) datas = sp.find_all('li', {'class':'mdCMN09Li FnStickerPreviewItem static-sticker'}) # 建立目錄儲存圖片 images_dir= "line_image/" if not os.path.exists(images_dir): os.mkdir(images_dir) for data in datas: imginfo = json.loads(data.get('data-preview')) id = imginfo['id'] imgfile = requests.get(imginfo['staticUrl']) full_path = images_dir + id + '.png' with open(full_path, 'wb') as f: f.write(imgfile.content) print(full_path) ``` ```python= #stickershop 完整 import requests, json, os from bs4 import BeautifulSoup #url = 'https://store.line.me/stickershop/product/8991459/zh-Hant' #人的日常 url = 'https://store.line.me/stickershop/product/24885624/zh-Hant' #喵咪跟兔嘰 html = requests.get(url) sp = BeautifulSoup(html.text, 'html.parser') datas = sp.find_all('li', {'class':'mdCMN09Li FnStickerPreviewItem static-sticker'}) imges_dir = "line_image/" if not os.path.exists(imges_dir): os.mkdir(imges_dir) for data in datas: imginfo = json.loads(data.get('data-preview')) id = imginfo['id'] imgfile = requests.get(imginfo['staticUrl']) full_path = imges_dir + id + '.png' with open(full_path, 'wb') as f: f.write(imgfile.content) print(full_path) ``` 【afterclass practice】 ( A ) 1. 以open(filename[,mode][,encode]) 開啟檔案,下列何者是 mode 參數預設的模式? (A) 讀取模式 (B) 寫入模式 (C) 附加模式 (D)以上皆是 ( C ) 2. Python 提供何種內建函式,可以開啟指定的檔案,以便進行檔案內容的讀取、寫入或修改? (A) file() (B) input() (C) open() (D) output() ( B ) 3. 下列何函式可以讀取一列字元? (A) readable() (B) read() (C) readlines() (D)get(ch) ( B ) 4. 下列程式建立的檔案物件,可以執行何種動作? ```python= f=open('file1.txt','w') f.write("Hello Python!") f.close() ``` (A) 讀取 (B) 寫入 (C) 可讀取也可寫入 (D) 以上皆非 ( D ) 5. 執行下列程式,下列顯示結果何者正確? ```python= 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 ( A ) 6. open(filename,mode,encode) 函式的參數中,其中只有那一個參數是必填? (A) filename (B) mode (C) encode (D) 以上皆是 ( B ) 7. 如果作業系統是繁體中文 Windows 系統,預設的編碼為何? (A) UTF-8 (B) cp950 (C) unicode (D) GB2312 ( D ) 8. 下列有關 readlines() 的敘述,何者正確? (A) 會讀取全部文件內容 (B) 以串列方式傳回 (C) 包括「\n」跳列字元,甚至是隱含的字元 (D) 以上皆是 ( A ) 9. 執行下列程式,下列顯示結果何者正確? ```python= n=1 try: print(n) except: print("變數不存在!") ``` (A) 1 (B) n © 變數不存在 (D) 以上皆是 ```python= n=1 try: print(n) except: print("變數不存在!") ``` 1 ( C ) 10. 班上的除錯高手大匹,在他的程式中加入了錯誤的補捉在 try…except…finally 敘述中,無論例外有沒有發生都會執行下列那些程式區塊? (A) try (B) except (C) finally (D) 以上皆是