Guardian Part

本文探讨了使用Python处理邮件日志的技巧,通过增加保护模块避免程序因空行引发错误,介绍了两种有效的方法来读取和解析包含From关键字的mbox-short文件行,确保代码稳定运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

TIPS
关于Guardian Part

'''
用另一种写法来读取mbox-short当中的from
'''

fhandle = open('mbox-short.txt')
for line in fhandle:
    line = line.rstrip()
    wds = line.split()
    if wds[0] != 'From':
        print('ignore')

这里会报错:
File “E:/TESTS/PYTHON/Guardian_part/guardian_part.py”, line 9, in
if wds[0] != ‘From’:
IndexError: list index out of range

debug:

fhandle = open('mbox-short.txt')
for line in fhandle:
    line = line.rstrip()
    wds = line.split()
    print('word: ' , line)  #DEBUG
    if wds[0] != 'From':
        continue
    else:
    	print('From Line')

可以发现源文件当中有空行,这样的话wds[0]本身就是不存在的了

所以解决方法是加保护模块:

'''
用另一种写法来读取mbox-short当中的from
'''

fhandle = open('mbox-short.txt')
for line in fhandle:
    line = line.rstrip()
    wds = line.split()
    print('word: ' , line)
    if len(line) == 0:
        continue           #保护模块
    if wds[0] != 'From':
        continue
    else:
    	print('From Line')

或者这样写:

fhandle = open('mbox-short.txt')
for line in fhandle:
    line = line.rstrip()
    wds = line.split()
    #print('word: ' , line)
    if len(line) == 0 or wds[0] != 'From':
        continue
    else:
        print('From Line')

注意:
如果写成

 if wds[0] != 'From' or len(line) == 0 :

同样会报错,因为率先执行了wds[0] != ‘From’,所以空行没有被率先排除,所以依然会报错。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值