# 請讀取name.txt
# 將文字儲存於List內容
# 每次執行可以亂數產生3個名字
# 陳怡伶
# 馮芳如
# 蒙淑惠
# 張軒宸
# 陳向愛 # 賴心怡 # 王怡珊 # 林詠斌 # 陳淑娟 # 崔孝憲
import random as rnd
student: list = []
def readfile():
# 開啟檔案,讀取模式(r),用 UTF-8 編碼避免亂碼
f = open('./names.txt', 'r', encoding='utf-8')
# 用 for 逐行讀取檔案內容
for line in f:
# 把每一行多餘的換行符號去掉(避免出現名字\n)
name = line.strip()
# 如果這一行不是空的,再加入 student 名單
if name != '':
student.append(name)
# 記得關掉檔案,釋放資源
f.close()
def readfile():
with open('./names.txt', 'r', encoding='utf-8') as f:
for line in f:
name = line.strip()
if name:
student.append(name)
自動關閉檔案,不需要再寫 readfile.close()
更安全,萬一中途錯誤也會自動釋放資源
readfile()
# 隨機選 3 個學生
result = rnd.sample(student, 3)
print("🎲 隨機抽出的名字:")
for i in result:
print(i)
✅ 厲害的寫法,用return
def readfile():
with open('names.txt', 'r', encoding='utf-8') as f:
return [line.strip() for line in f if line.strip()]
Pythonic 的寫法代表之一!🎯🐍
你這樣感覺對了,代表你已經開始具備「寫得漂亮、效率又高」的寫程式直覺了!
✅ 如果少了name = line.strip(),而是name = line那就會變成這樣
['陳怡伶\n馮芳如\n蒙淑惠\n張軒宸\n...']
這就變成只有「一筆資料」,而不是你想要的「10 個名字」,導致 random.sample(student, 3) 出錯或選不到 3 個。