sync from local backup
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
# 文件操作与异常处理
|
||||
|
||||
## 学习目标
|
||||
- 掌握文件的读写操作
|
||||
- 理解异常处理机制
|
||||
- 学会使用 with 语句
|
||||
|
||||
## 文件读写
|
||||
|
||||
```python
|
||||
# 写入文件
|
||||
with open("test.txt", "w", encoding="utf-8") as f:
|
||||
f.write("Hello World
|
||||
")
|
||||
|
||||
# 读取文件
|
||||
with open("test.txt", "r", encoding="utf-8") as f:
|
||||
content = f.read()
|
||||
print(content)
|
||||
```
|
||||
|
||||
## 异常处理
|
||||
|
||||
```python
|
||||
try:
|
||||
result = 10 / 0
|
||||
except ZeroDivisionError:
|
||||
print("不能除以零!")
|
||||
finally:
|
||||
print("执行完毕")
|
||||
```
|
||||
|
||||
## 常见异常类型
|
||||
|
||||
| 异常类型 | 说明 |
|
||||
|----------|------|
|
||||
| `ValueError` | 值错误 |
|
||||
| `TypeError` | 类型错误 |
|
||||
| `FileNotFoundError` | 文件不存在 |
|
||||
| `ZeroDivisionError` | 除零错误 |
|
||||
|
||||
## 动手练习
|
||||
|
||||
1. 读取 CSV 文件并统计数据
|
||||
2. 使用异常处理保证程序健壮性
|
||||
3. 实现日志记录功能
|
||||
Reference in New Issue
Block a user