---
# System prepended metadata

title: wk15_1214_檔案與例外處理
tags: [python]

---

# wk15_1214_ch09_檔案與例外處理_B1003205醫放三謝彤

## [inclass practice]


```python
## chatGpt  local jpg
import shutil

source_path = r'C:\zzz\111.png'
destination_path = r'C:\zzz\1.png'

# 複製文件
shutil.copyfile(source_path, destination_path)

print(f'已從 {source_path} 複製到 {destination_path}')
```

    已從 C:\zzz\111.png 複製到 C:\zzz\1.png
    


```python
## chatGpt line png

import requests
import os

url = 'https://stickershop.line-scdn.net/stickershop/v1/sticker/230054638/android/sticker.png?v=1'
save_path = r'C:\zzz\3.jpg'

#response = requests.get(url, stream=True)
response = requests.get(url)

with open(save_path, 'wb') as file:
    for chunk in response.iter_content(chunk_size=8192):
        file.write(chunk)

print(f'已從 {url} 下載並保存到 {save_path}')

```

    已從 https://stickershop.line-scdn.net/stickershop/v1/sticker/230054638/android/sticker.png?v=1 下載並保存到 C:\zzz\3.jpg
    


```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/30084/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)  
```

    line_image/637043806.png
    line_image/637043807.png
    line_image/637043808.png
    line_image/637043809.png
    line_image/637043810.png
    line_image/637043811.png
    line_image/637043812.png
    line_image/637043813.png
    line_image/637043814.png
    line_image/637043815.png
    line_image/637043816.png
    line_image/637043817.png
    line_image/637043818.png
    line_image/637043819.png
    line_image/637043820.png
    line_image/637043821.png
    line_image/637043822.png
    line_image/637043823.png
    line_image/637043824.png
    line_image/637043825.png
    line_image/637043826.png
    line_image/637043827.png
    line_image/637043828.png
    line_image/637043829.png
    line_image/637043830.png
    line_image/637043831.png
    line_image/637043832.png
    line_image/637043833.png
    line_image/637043834.png
    line_image/637043835.png
    line_image/637043836.png
    line_image/637043837.png
    line_image/637043838.png
    line_image/637043839.png
    line_image/637043840.png
    line_image/637043841.png
    line_image/637043842.png
    line_image/637043843.png
    line_image/637043844.png
    line_image/637043845.png
    

### 凱薩密碼

參考文件: https://github.com/CrypTools/CaesarCipher


```python
import string
import matplotlib.pyplot as plt

LETTERS = 'abcdefghijklmnopqrstuvwxyz,.() '

def encrypt(initial, shift):
  initial = initial.lower()
  output = ""

  for char in initial:
    if char in LETTERS:
      output += LETTERS[(LETTERS.index(char) + shift) % len(LETTERS)]

  return output

def decrypt(initial, shift):
  initial = initial.lower()
  output = ""

  for char in initial:
    if char in LETTERS: #密鑰(key)即shift量
      output += LETTERS[(LETTERS.index(char) - shift) % len(LETTERS)]
      
  return output

def plot_letter_frequency(text):
    text = text.lower()
    letter_count = {letter: 0 for letter in string.ascii_lowercase}

    for char in text:
        if char.isalpha():
            letter_count[char] += 1

    letters = list(letter_count.keys())
    counts = list(letter_count.values())

    plt.bar(letters, counts)
    plt.xlabel('Letters')
    plt.ylabel('Frequency')
    plt.title('Letter Frequency in Text')
    plt.savefig('./result.png')

## ---------------  Main  ------------------
message = input('請輸入要加密的訊息: ')
key = int(input('請輸入密鑰: '))

# 加密
cipher = encrypt(message, key)
print(f'\n加密結果: {cipher}')

# 解密
plain = decrypt(cipher, key)
print(f'\n解密結果: {plain}')

#字數統計
plot_letter_frequency(cipher)
```

    請輸入要加密的訊息: ABCD
    請輸入密鑰: 3
    
    加密結果: defg
    
    解密結果: abcd
    


    
![png](output_6_1.png)
    


## [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.下列程式建立的檔案物件，可以執行何種動作?

(A)讀取 (B)寫入 (C)可讀取也可寫入 (D)以上皆非

Answer:(B)


```python
f=open('file1.txt','w')
f.write("Hello Python!")
f.close()
```

5.執行下列程式，下列顯示結果何者正確?

(A)x (B)y (C)xz (D)yz

Answer:(D)


```python
try:
    print(x)
except:
    print("y")
finally:
    print("z")
```

    y
    z
    

6.open(filename,mode,encode)函式的參數中，其中只有哪一個參數是必填?

(A)filename (B)mode (C)encode (D)以上皆是

Answer:(A)

7.如果作業系統是繁體中文Window系統，預設的編碼為何?

(A)UTF-8 (B)cp950 (C)unicode (D)GB2312

Answer:(B)

8.下列有關readlines()的敘述，何者正確?

(A)會讀取全部文件內容 (B)以串列方式傳回 (C)包括「\n」跳列字元，甚至是隱含的字元 (D)以上皆是

Answer:(D)

9.執行下列程式，下列顯示結果何者正確?

(A)1 (B)n (C)變數不存在 (D)以上皆是

Answer:(A)


```python
n=1
try:
    print(n)
except:
    print("變數不存在!")
```

    1
    

10.班上的除錯高手大匹，在他的程式中加入了錯誤的捕捉在try...except...finally敘述中，無論例外有沒有發生都會執行下列哪些程式區塊?

(A)try (B)except (C)finally (D)以上皆是

Answer:(C)

### 教學影音

try:程式碼A...except:程式碼B...else:程式碼C...finally:程式碼D\
else和finally不是必填的。\
程式碼A:用來執行並進行例外偵測\
程式碼B:若有發生例外，要執行的程式\
程式碼C:若沒發生例外，要執行的程式\
程式碼D:一定會執行的程式

## [self practice]

json套件是為了讓html解讀動態貼圖

sp是我們能解讀的格式

li是一張圖所佔據的項目

with open 可打開檔案並執行，執行結束後自動關掉，避免佔據過多記憶體