python3基础:异常处理及python常见异常类型总结

1、try...except...

#!/usr/bin/env python
# coding=utf-8
import codecs


def get_webinfo(path):
    web_info = {}
    with codecs.open(path, 'r', 'utf-8') as config:
        for line in config.readlines():
            # 遍历文件中每一行并以“=”分隔,再做列表解析,使用for循环去掉换行符,并以列表形式返回
            result = [ele.strip() for ele in line.split(';', 1)]
            # 先使用dict()将嵌套列表'[result]'转换成字典,再使用update更新字典
            web_info.update(dict([result]))
            print(web_info)
        return web_info

try:
    get_webinfo('D:/userinfo.txt1')
except IOError as msg:
    print('文件出错了,原因是:' + str(msg))


运行结果是:文件出错了,原因是:[Errno 2] No such file or directory: 'D:/userinfo.txt1'

发布了52 篇原创文章 · 获赞 13 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/yijinaqingan/article/details/85269911
今日推荐