👉 项目官网:https://www.python-office.com/ 👈

github star

大家好,这里是程序员晚枫,正在all in AI编程实战

今天我们学习 Python 的错误处理和调试技巧,让你的程序更稳定!

1、什么是错误?

Python 代码运行时会遇到各种错误:

1
2
3
4
5
6
7
8
# 除零错误
print(10 / 0) # ZeroDivisionError

# 文件不存在
open('不存在的文件.txt') # FileNotFoundError

# 类型错误
print('hello' + 123) # TypeError

2、用try-except处理错误

1
2
3
4
5
6
try:
# 尝试执行这段代码
result = 10 / 0
except ZeroDivisionError:
# 如果出错,执行这段
print('除数不能为零!')

3、完整的错误处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
try:
# 尝试读取文件
with open('data.txt', 'r') as f:
content = f.read()
except FileNotFoundError:
print('文件不存在!')
except PermissionError:
print('没有权限读取文件!')
except Exception as e:
print(f'发生错误:{e}')
else:
# 没有错误时执行
print('读取成功!')
finally:
# 无论有没有错都执行
print('程序结束')

4、在办公自动化中的错误处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import office

def safe_read_excel(file_path):
"""安全读取Excel"""
try:
df = office.excel.read(path=file_path)
return df
except FileNotFoundError:
print(f'文件不存在:{file_path}')
return None
except Exception as e:
print(f'读取失败:{e}')
return None

def safe_send_email(recipient, title, content):
"""安全发送邮件"""
try:
office.email.send(email=recipient, title=title, content=content)
print(f'邮件已发送给:{recipient}')
except Exception as e:
print(f'发送失败:{e}')

5、用日志记录错误

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import logging

# 配置日志
logging.basicConfig(
level=logging.INFO,
filename='error.log',
format='%(asctime)s - %(levelname)s - %(message)s'
)

def process_file(file_path):
try:
df = office.excel.read(path=file_path)
return df
except Exception as e:
logging.error(f'处理文件失败:{file_path} - {e}')
return None

# 运行
process_file('data.xlsx')

6、调试技巧

打印调试

1
2
3
4
5
def calculate(data):
print(f'输入数据:{data}') # 打印中间值
result = sum(data) / len(data)
print(f'计算结果:{result}')
return result

使用assert断言

1
2
3
def divide(a, b):
assert b != 0, '除数不能为零' # 断言检查
return a / b

7、实战案例:稳健的数据处理脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import office
import logging
from datetime import datetime

# 配置日志
logging.basicConfig(
level=logging.INFO,
filename=f'处理日志_{datetime.now().strftime("%Y%m%d")}.log'
)

def process_daily_data(file_path):
"""处理每日数据,带完整错误处理"""

try:
# 1. 读取数据
logging.info(f'开始处理:{file_path}')
df = office.excel.read(path=file_path)
logging.info(f'读取成功,共{len(df)}条记录')

# 2. 处理数据
df['日期'] = datetime.now().strftime('%Y-%m-%d')
logging.info('数据处理完成')

# 3. 保存结果
output = f'处理结果_{datetime.now().strftime("%Y%m%d")}.xlsx'
office.excel.write(path=output, data=df.values.tolist())
logging.info(f'结果已保存:{output}')

return True

except FileNotFoundError as e:
logging.error(f'文件不存在:{e}')
return False
except KeyError as e:
logging.error(f'列名错误:{e}')
return False
except Exception as e:
logging.error(f'未知错误:{e}')
return False

# 处理多个文件
files = ['1.xlsx', '2.xlsx', '3.xlsx']
for f in files:
success = process_daily_data(f)
print(f'{f}: {"成功" if success else "失败"}')

8、常见错误及解决方案

错误类型常见原因解决方案
FileNotFoundError文件路径错误检查文件是否存在
PermissionError文件被占用关闭文件后再运行
TypeError类型不匹配检查数据类型
KeyError字典键不存在使用get()方法
UnicodeDecodeError编码问题指定encoding='utf-8'

9、总结

错误处理的三板斧:

  • try - 尝试执行
  • except - 捕获错误
  • else - 没有错误时执行

日志是最好的调试工具!

10、下讲预告

学会了错误处理,下一讲我们学 打包Python程序:把脚本做成exe可执行文件。

敬请期待!


有问题欢迎加微信 python-office 进群交流~

程序员晚枫专注AI编程培训,小白看完他和图灵社区合作的教程《30讲 · AI编程训练营》就能上手做AI项目。

🎓 AI 编程实战课程

想系统学习 AI 编程?程序员晚枫的 AI 编程实战课 帮你从零上手!