上一期小練習解答(第5期回顧)
? 練習1:字符串反轉模塊 string_tools.py
# string_tools.py
def reverse_string(s):return s[::-1]
調用:
import string_tools
print(string_tools.reverse_string("Hello")) # 輸出 "olleH"
? 練習2:創建包 my_math
目錄結構:
my_math/
├── __init__.py
├── basic.py
└── advanced.py
my_math/basic.py
def add(a, b):return a + b
?my_math/advanced.py
import mathdef sqrt(x):return math.sqrt(x)
調用方式:
from my_math import basic, advanced
print(basic.add(2, 3)) # 輸出 5
print(advanced.sqrt(16)) # 輸出 4.0
? 練習3:隨機驗證碼
import random
import stringdef generate_code(length=6):chars = string.ascii_letters + string.digitsreturn ''.join(random.choice(chars) for _ in range(length))print(generate_code()) # 示例輸出:a8B2kZ
?
本期主題:文件操作與文本處理
🟦 6.1 打開文件
Python 使用內置的 open()
函數來打開文件。
f = open("example.txt", "r") # 讀取模式
常見模式:
模式 | 含義 |
---|---|
'r' | 只讀(默認) |
'w' | 寫入(會清空原文件) |
'a' | 追加 |
'b' | 二進制模式 |
'+' | 讀寫模式 |
6.2 讀取文件內容
f = open("example.txt", "r")
content = f.read()
print(content)
f.close()
? 更推薦的寫法:使用 with
自動關閉文件
with open("example.txt", "r") as f:content = f.read()print(content)
其他讀取方式:
f.readline() # 讀取一行
f.readlines() # 讀取所有行,返回列表
?6.3 寫入文件
with open("output.txt", "w") as f:f.write("Hello, Python!\n")f.write("Let's write some text.\n")
注意:如果文件存在,"w"
模式會清空原文件內容。
6.4 文本處理技巧
? 字符串切片
text = "Hello, Python"
print(text[7:]) # 輸出 Python
?? 字符串替換
text = "I like apple"
new_text = text.replace("apple", "banana")
print(new_text) # I like banana
? 拆分和合并
s = "apple,banana,grape"
lst = s.split(",") # ['apple', 'banana', 'grape']
joined = "-".join(lst)
print(joined) # apple-banana-grape
? 去除空白
s = " hello \n"
print(s.strip()) # 輸出 "hello"
附加:處理中文文件
with open("cn.txt", "r", encoding="utf-8") as f:content = f.read()print(content)
with open("cn_out.txt", "w", encoding="utf-8") as f:f.write("你好,世界")
本期小練習
-
寫一個程序,讀取文件
data.txt
,并統計文件中總共有多少行。 -
寫一個程序,讀取文件中的每一行,并將其反轉后寫入到
reversed.txt
文件中。 -
寫一個程序,從一個包含姓名的文件中篩選出所有以 "A" 開頭的名字,寫入
a_names.txt
。
小結
這一期我們學習了:
-
文件的打開、讀取、寫入
-
with
的使用 -
文本處理中的字符串操作
-
編碼問題的處理方法
你現在可以開始處理文本文件、做一些簡單的文本清洗、數據預處理任務了!
第7期預告:
下一期我們將探討:
-
列表推導式和字典推導式
-
更優雅地構造數據結構
-
實際例子演練:快速處理文本數據
?
?
?
?
?
?
?
?