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

大家好,这里是程序员晚枫,正在all in AI编程实战。
今天我们学习 Python 的错误处理和调试技巧,让你的程序更稳定!
1、什么是错误?
Python 代码运行时会遇到各种错误:
1 2 3 4 5 6 7 8
| print(10 / 0)
open('不存在的文件.txt')
print('hello' + 123)
|
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: logging.info(f'开始处理:{file_path}') df = office.excel.read(path=file_path) logging.info(f'读取成功,共{len(df)}条记录') df['日期'] = datetime.now().strftime('%Y-%m-%d') logging.info('数据处理完成') 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 编程实战课 帮你从零上手!