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文件读写基本用法