
學習到這個階段,大家如果都有跟上的話已經可以試著自行開發一些工具或是演算法了。不過Python還有提供許多進階的功能可以幫助我們在開發的過程中更順暢、更有效率。
⚠️ 例外處理 (Exception)
不論你是初學者還是資深工程師,在整個程式開發的過程中就是不斷地Debug Debug,有些Bug可以預先設想到,有些則是預期之外的Bug。這些意料之外的Bug非常容易造成程式崩潰,同時你的客戶也會跟著崩潰,最後就換你崩潰了。
能不能有一些機制可以讓我們在開發過程中可以捕捉到更多Bug,降低程式崩潰的機率❓
接下來要介紹的Python 例外處理,可以讓我們了解如何捕捉錯誤以增強程式穩定性,減少各位在開發過程中崩潰的次數。
使用 try-except
捕捉錯誤
程式執行時可能會遇到意料之外的錯誤,例如輸入錯誤、檔案不存在等。例外處理 提供了一種方式來捕捉和應對這些錯誤,從而防止程式崩潰。
# 基本語法
try:
# 嘗試執行可能出錯的代碼
risky_operation()except SpecificError:
# 當發生指定錯誤時執行的代碼
handle_error()
# 範例
try:
number = int(input("Enter a number: "))
print(f"The number you entered is: {number}")
except ValueError:
print("Invalid input! Please enter a valid number.")
# 輸出
Enter a number: abcInvalid input! Please enter a valid number.
else / finally搭配
- else:當 try 區塊 沒有觸發例外 時執行。
- finally:無論是否發生例外,都會執行,用於釋放資源或執行收尾工作。
try:
number = int(input("Enter a number: "))
except ValueError:
print("Invalid input!")
else:
print(f"You entered: {number}")
finally:
print("Execution completed.")
# 輸出
Enter a number: 123
You entered: 123
Execution completed.
常見例外類型

自定義例外 (Custom Exceptions)
除了使用已經定義好的例外類型,還可以透過繼承Exception類別來自定義新的例外類型。繼承是一種進階的Python技巧,後續的文章中會再詳細說明。
class InvalidAgeError(Exception):
"""當年齡無效時引發的例外"""
def __init__(self, age):
self.age = age
super().__init__(f"Invalid age: {age}. Age must be between 0 and 120.")
# 使用範例
def check_age(age):
if age < 0 or age > 120:
raise InvalidAgeError(age)
try:
check_age(150) # 傳入無效年齡,會引發 InvalidAgeError
except InvalidAgeError as e:
print(f"InvalidAgeError caught: {e}")
#輸出
InvalidAgeError caught: Invalid age: 150. Age must be between 0 and 120.
📂 檔案操作
檔案讀取與儲存是程式開發中一定會做的事情,除了使用numpy讀取np.array、pandas讀取excel等特定格式檔案之外,也可以使用python內建的功能來操作各種檔案。
with open
安全管理檔案操作
with open
是Python獨有的語法,能自動管理檔案的關閉操作,避免忘記關閉文件而導致資源洩漏,建議一律使用此方式來進行檔案操作。
# 寫入文件
with open("example.txt", "w") as file:
file.write("This is managed by 'with open'")
# 讀取文件
with open("example.txt", "r") as file:
content = file.read()
print(content)
# 輸出
This is managed by 'with open'
檔案開啟模式
以下是 open()
函數支援的常見模式:

# 使用 'w' 寫入模式
with open("test.txt", "w") as file:
file.write("Hello, World!\n")
# 使用 'a' 追加模式
with open("test.txt", "a") as file:
file.write("Adding another line.\n")
# 使用 'r' 讀取模式
with open("test.txt", "r") as file:
content = file.read()
print(content)
# 輸出
執行結果:
Hello, World!
Adding another line.
閱讀檔案內容
# example.txt
Hello, World!
Python is awesome.
This is a test file.
逐字串讀取 (read())
- 讀取整個檔案內容,或僅讀取指定的字節數
with open("example.txt", "r") as file:
content = file.read(10) # 讀取前 10 個字元
print(content)
# 輸出
Hello, Wor
逐行讀取 (readline() 與 readlines())
- readline():每次讀取一行。
- readlines():一次性讀取所有行並返回列表,每行作為一個元素。
# 程式碼
with open("example.txt", "r") as file:
line = file.readline() # 讀取第一行
print(f"First Line: {line.strip()}")
file.seek(0) # 回到檔案開頭
all_lines = file.readlines() # 讀取所有行
print("Remaining Lines:")
for line in all_lines:
print(line.strip())
# 輸出
First Line: Hello, World!
Remaining Lines:
Hello, World!
Python is awesome.
This is a test file.
迴圈逐行讀取
- 每次讀取一行,內存效率更高
# 程式碼
with open("example.txt", "r") as file:
print("Reading lines using for loop:")
for line in file:
print(line.strip())
# 輸出
Reading lines using for loop:
Hello, World!
Python is awesome.
This is a test file.
寫入檔案內容
write() 寫入資料
- 清空文件後寫入新內容
# 程式碼
with open("example.txt", "w") as file:
file.write("First line.\n")
file.write("Second line.\n")
# 確認內容
with open("example.txt", "r") as file:
print(file.read())
# 輸出
First line.
Second line.
writelines() 寫入多行
- 將多行內容一次性寫入文件
# 程式碼
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("example.txt", "w") as file:
file.writelines(lines)
# 確認內容
with open("example.txt", "r") as file:
print(file.read())
# 輸出
Line 1
Line 2
Line 3
檔案刪除
- 使用os.path.exists()判斷檔案是否存在
- 使用os.remove()刪除檔案
import os
# 程式碼
if os.path.exists("example.txt"):
os.remove("example.txt")
print("File deleted.")
else:
print("File does not exist.")
# 輸出
File deleted.
JSON 檔案處理
目前來說,開發時最常使用的檔案格式非JSON格式莫屬了!
- JSON (JavaScript Object Notation) 是一種輕量級的數據交換格式,專為易讀性與結構性而設計
- 最初基於 JavaScript 的語法,現在已成為一種獨立於語言的通用數據格式,被廣泛應用於網頁開發、API 通訊等場景
- 常用於API資料傳輸、前後端資料交換等任務
特性
- 輕量化:簡單且易於解析,專為數據交換設計。
- 可讀性強:人類可直接閱讀,方便理解與編輯。
- 跨平台:支持多種編程語言(如 Python、Java、JavaScript)。
- 結構化數據:通過鍵值對和數組來形成樹狀結構,適合層級數據存儲與傳輸。
常見格式規則

JSON格式範例
{
"name": "Alice",
"age": 25,
"address": {
"city": "New York",
"zip_code": "10001"
}
}
JSON檔案操作

import json
# 寫入 JSON 文件
data = {"name": "Alice", "age": 25, "is_student": False}
with open("data.json", "w") as file:
json.dump(data, file)
# 讀取 JSON 文件
with open("data.json", "r") as file:
loaded_data = json.load(file)
print(loaded_data)