python文件读写之异常处理

python文件读写之异常处理

​ 使用文件时,一种常见的问题是找不到文件:你要查找的文件可能在其他地方、文件名可能不正确或者这个文件根本就不存在。对于所有这些情形,都可使用try-except代码块以直观的方式进行处理 。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date    : 2020-11-12 15:58:46
# @Author  : EricRay
# @Email   : ericray.tech@outlook.com
# @Link    : https://blog.csdn.net/ericleiy/
# @Description 统计字符及抛出异常


def count_words(filename):
    try:
        with open(filename) as file_object:
            contents = file_object.read()
    except FileNotFoundError:
        msg = "Sorry, the file " + filename + " does not exist."
        print(msg)
    else:
        words = contents.split()
        num_words = len(words)
        print("The file " + filename + " has about " + str(num_words) +
              " words.")

"""
try代码块引发FileNotFoundError异常,因此Python找出与该错误匹配的
except代码块,并运行其中的代码。最终的结果是显示一条友好的错误消息,而不是traceback
"""

filename = 'alice.txt'
count_words(filename)

filenames = ['alice.txt', 'siddhartha.txt',
             'moby_dick.txt', 'little_women.txt']
for filename in filenames:
    count_words(filename)

# 本示例中 little_women.txt文件不存在

异常抛出简单示例

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2020-11-13 09:44:43
# @Author  : EricRay
# @Email   : ericray.tech@outlook.com
# @Link    : https://blog.csdn.net/ericleiy/
# @Description :循环输入两个数字,判断是否为数字,并抛出异常

print("Please give me two number, and i'll add them.")
print("Enter 'q' to quit.")

while True:
    first_number = input("\nFirst number:")
    if first_number == 'q':
        break
    second_number = input("\nSecond number:")
    if second_number == 'q':
        break
    try:
        answer = int(first_number) + int(second_number)
    except ValueError:
        print("The input must be number,please check them!")
    else:
        print("The sum of " + str(first_number) + " and " +
              str(second_number) + " is " + str(answer))

python文件相关操作参考:python文件读写基本用法

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值