上一期小练习解答(第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 math
def 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 string
def generate_code(length=6):
    chars = string.ascii_letters + string.digits
    return ''.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期预告:
下一期我们将探讨:
-  列表推导式和字典推导式 
-  更优雅地构造数据结构 
-  实际例子演练:快速处理文本数据 



















