### wk15_1214_檔案與例外處理_line貼圖收集器 #### ch09_檔案與例外處理 - 9.1 檔案的操作 開啟檔案的語法 開啟檔案的模式 使用with...as 語法 檔案處理 - 9.2 檔案和目錄管理 os.path 模組 os 模組 - 9.3 例外處理 try...except...else...finally 語法 try...except...else...finally 使用方法 try...except 常用錯誤表 #### 【inclass practice】 ##### {綜合演練} - 實作1 : 小智以readlines()函式讀取文字檔<in_a.txt>,計算出每一列的字元數(包括結束字元),並在每一列前面顯示 - 實作5 : 阿吉得到大福真傳後很高興的執行前例自己完成的程式,但他發現當輸入正整數12可正確執行,可以顯示1、2、...、12,但輸入正數12.5後,程式又會出錯並且中斷執。他想了很久還是不解,明明是輸入正數數值,為何會出現錯誤,於是又求救於大福,大福教他已except Exception as e 捕捉錯誤的資訊。 ##### {範例} 以讀取模式開啟檔案並顯示資料 <fileread1> 以with...as語法開啟檔案並顯示資料 <fileread2> 在每段文章的前面加上編號 <Addlineno> 輸入兩個正整數求和,捕捉輸入的錯誤 <tryadd> 捕捉飛數值資料和除數為0的錯誤 <trymod> ```python file = "in_a.txt" with open(file,'r') as f: content=f.readlines() for row in content: n = len(row) print("字元數=%2s : %s" %(n,row)) ``` ```python try: n=float(input("請輸入正數 n:")) n=int(n) for i in range(1,n+1): print(i,end=" ") except Exception as e: print("發生錯誤的原因:" , e) ``` 請輸入正數 n:3 1 2 3 ##### 期末專題參考 - {實戰#5} : 凱薩密碼加密/解密 - {實戰#6} : line貼圖收集器 【oneDrive】課程資源 (密碼 : 1121python)/00_Python大數據特訓班(第二版)/教學影片/videos/ch07/ ```python import requests, json, os from bs4 import BeautifulSoup url = 'https://store.line.me/stickershop/product/8991459/zh-Hant' html = requests.get(url) html ``` <Response [200]> ```python sp = BeautifulSoup(html.text, 'html.parser') datas = sp.find_all('li', {'class':'mdCMN09Li FnStickerPreviewItem'}) # 建立目錄儲存圖片 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 # lineimage.py import requests,os,json from bs4 import BeautifulSoup url = 'https://store.line.me/stickershop/product/8991459/zh-Hant' html = requests.get(url) soup = BeautifulSoup(html.text,'html.parser') # 建立目錄儲存圖片 images_dir= "line_image/" if not os.path.exists(images_dir): os.mkdir(images_dir) # 下載貼圖 datas = soup.find_all('li', {'class':'mdCMN09Li FnStickerPreviewItem'}) for data in datas: # 將字串資料轉換為字典 imginfo = json.loads(data.get('data-preview')) id=imginfo['id'] imgfile = requests.get(imginfo['staticUrl']) #載入圖片 full_path = os.path.join(images_dir,id) #儲存的路徑和主檔名 # 儲存圖片 with open(full_path + '.png', 'wb') as f: f.write(imgfile.content) print(full_path + '.png') #顯示儲存的路徑和檔名 ``` ```python 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) ``` line_image/632876774.png line_image/632876775.png line_image/632876776.png line_image/632876777.png line_image/632876778.png line_image/632876779.png line_image/632876780.png line_image/632876781.png line_image/632876782.png line_image/632876783.png line_image/632876784.png line_image/632876785.png line_image/632876786.png line_image/632876787.png line_image/632876788.png line_image/632876789.png line_image/632876790.png line_image/632876791.png line_image/632876792.png line_image/632876793.png line_image/632876794.png line_image/632876795.png line_image/632876796.png line_image/632876797.png line_image/632876798.png line_image/632876799.png line_image/632876800.png line_image/632876801.png line_image/632876802.png line_image/632876803.png line_image/632876804.png line_image/632876805.png line_image/632876806.png line_image/632876807.png line_image/632876808.png line_image/632876809.png line_image/632876810.png line_image/632876811.png line_image/632876812.png line_image/632876813.png ```python #表情貼-1 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' #喵咪跟兔嘰 url = 'https://store.line.me/emojishop/product/646b23ff903b5543729ffa4d/zh-Hant' #超實用❤生活用語對話框 #url = 'https://store.line.me/emojishop/product/61b04cbaf864dd7f3763ab8b/zh-Hant' #超實用❤手勢/符號 動態表情貼 html = requests.get(url) html ``` <Response [200]> #### 【afterclass practice】 - 綜合演練 選擇題1-10 (需抄題在markdown cell ; 有程式碼的題目要有code cell ) - 教學影音 lesson 10 - 請填寫小組報告主題 --- 【期末小組】管理 - 請填寫筆記網站網址 --- 【OMP】問卷 <pre> 1. 以open(filename[,mode][,encode]) 開啟檔案,下列何者是 mode 參數預設的模式? (A) 讀取模式 (B) 寫入模式 (C) 附加模式 (D)以上皆是 Ans:( A ) 2. Python 提供何種內建函式,可以開啟指定的檔案,以便進行檔案內容的讀取、寫入或修改? (A) file() (B) input() (C) open() (D) output() Ans:( C ) 3. 下列何函式可以讀取一列字元? (A) readable() (B) read() (C) readlines() (D)get(ch) Ans:( B ) 4. 下列程式建立的檔案物件,可以執行何種動作? f=open('file1.txt','w') f.write("Hello Python!") f.close() (A) 讀取 (B) 寫入 (C) 可讀取也可寫入 (D) 以上皆非 Ans:( B ) 5. 執行下列程式,下列顯示結果何者正確? try: print(x) except: print("y") finally: print("z") (A) x (B) y (C) xz (D) yz Ans:( D ) 6. open(filename,mode,encode) 函式的參數中,其中只有那一個參數是必填? (A) filename (B) mode (C) encode (D) 以上皆是 Ans:( A ) 7. 如果作業系統是繁體中文 Windows 系統,預設的編碼為何? (A) UTF-8 (B) cp950 (C) unicode (D) GB2312 Ans:( B ) 8. 下列有關 readlines() 的敘述,何者正確? (A) 會讀取全部文件內容 (B) 以串列方式傳回 (C) 包括「\n」跳列字元,甚至是隱含的字元 (D) 以上皆是 Ans:( D ) 9. 執行下列程式,下列顯示結果何者正確? n=1 try: print(n) except: print("變數不存在!") (A) 1 (B) n (C) 變數不存在 (D) 以上皆是 Ans:( A ) 10. 班上的除錯高手大匹,在他的程式中加入了錯誤的補捉在 try…except…finally 敘述中,無論例外有沒有發生都會執行下列那些程式區塊? (A) try (B) except (C) finally (D) 以上皆是 Ans:( C ) <pre/> ```python #5. 執行下列程式,下列顯示結果何者正確? try: print(x) except: print("y") finally: print("z") ``` y z ```python #9. 執行下列程式,下列顯示結果何者正確? n=1 try: print(n) except: print("變數不存在!") ``` 1