目录
1. 异常基本知识
- 异常简介
- 异常的传播
2. 文件基本操作
课堂笔记
1. 异常基本知识
1.1 异常简介
-
程序在运行过程中出现的错误。如 使用不存在索引、除以0、类型问题等
-
异常处理:为了防止异常造成的程序终止运行而通过代码对异常进行处理的过程
-
基本语法:
try:
代码块(可能出现错误的语句)
except 异常类型 as 异常名:(except块可存在多个)
代码块(处理错误的语句)
else:
代码块(未出错时要处理的语句)
finally:
必须执行部分(无论异常与否,finally都会执行)
- try为必须部分,else可有可无,except和finally必须至少一个,但只有except部分能处理异常
1.2 异常的传播
- 当函数中出现异常时,若该函数对异常进行了处理,则异常不会进行传播,否则异常会依次向上传播给每一个调用处,若查找到异常处理,则不进行传播,否则一直到主模块,还是无异常处理,程序终止并显示异常信息
- 程序被处理的异常会被保存到一个异常对象中,因此异常传播实际上就是把一个对象抛给了调用处
# 定义除法函数
def div(a, b):
return a/b
# 定义一个主功能函数fun
def fun(n):
res = 0
for i in range(n):
res += div(1, i)
return res
if __name__ == '__main__':
print(fun(10))
'''
这里的代码会出现ZeroDivisionError: division by zero(除以0的错误)
由于主模块调用fun函数,fun函数调用div(1, 0)时会出现异常,然后div中未查找到对异常处理,
于是向上查找fun,也未找到,最后到__main__中,也为发现对异常的处理,于是程序终止,并依次显示异常信息
如下:
Traceback (most recent call last):
File "C:/Users/Administrator/PycharmProjects/new_demo/Exception.py", line 13, in <module>
print(fun(10))
File "C:/Users/Administrator/PycharmProjects/new_demo/Exception.py", line 9, in fun
res += div(1, i)
File "C:/Users/Administrator/PycharmProjects/new_demo/Exception.py", line 3, in div
return a/b
ZeroDivisionError: division by zero
'''
# 定义除法函数
def div(a, b):
return a/b
# 定义一个主功能函数fun
def fun(n):
res = 0
for i in range(n):
try:
res += div(1, i)
except Exception as e: # Exception为所有异常父类,可捕获所有异常
print(e) # division by zero
return res
if __name__ == '__main__':
print(fun(10)) # 2.8289682539682537
2. 文件基本操作
- 文件输入/输出(Input/Output)
- 文件操作步骤:
- 打开文件 open()
- 操作文件 read()/write()等
- 关闭文件 close()(防止空间浪费)
- 文件常用方法:
方法名 | 作用 |
---|---|
open(name, model, buffering) | 默认以纯文本形式打开文件,也可指定为二进制文件 |
close() | 关闭文件 |
read(n) | 默认读取整个文件内容,也可指定长度 |
readline(limit) | 以字符串形式返回一行,也可指定长度 |
readlines(limit) | 以列表形式返回多行,也可指定长度 |
write(s) | 以字符串形式写入文件,文件不存在会自动创建 |
writelines(lines) | 以一个序列的形式写入文件 |
tell() | 返回当前文件指针的位置,即读写文件内容的位置 |
seek(offset, whence) | whence默认为0,表示从文件开头偏移offset个字节,whence还可取1和2,表示从当前位置与末尾位置偏移 |
with…as | 一般以with open() as 的形式打开文件,不需要自己close() |
- 常见model取值
取值 | 含义 |
---|---|
r或rt | 默认模式,以文本模式读取内容 |
rb | 以二进制方式读取文件 |
w或wt | 文本写模式,打开文件前会被清空 |
wb | 以二进制方式写入文件,文件同样被清空 |
a | 在文件中进行文本追加 |
a+ | 可读写模式,只能在文件末尾写 |
w+ | 可读写模式,文件会提前被清空 |
r+ | 可读写模式,写的位置任意 |
- 文件打开与关闭
import io
# 以读的形式打开test.txt,此时会创建一个test.txt
f = io.open('test.txt', 'w', encoding='utf-8')
# 写入一段字符串,返回值为写入串的长度
res = f.write('Life is short, I love Python!')
# 关闭文件
f.close()
# 以读的形式打开文件,编码为utf-8
f = io.open('test.txt', 'r', encoding='utf-8')
# 指定读取长度为10的字符串
print(f.read(13)) # Life is short
# 默认读取整个文件内容
print(f.read()) # , I love Python!
# 关闭文件
f.close()
## 使用with...as
# with open('test.txt', 'r', encoding='utf-8') as f:
# print(f.readline()) # Life is short, I love Python!
- seek()与tell()方法(
seek()第二个参数非0时,读写格式必须为二进制类型
)
# test.txt内容 Hello World!
with open('test.txt', 'rb+') as f:
f.seek(5, 1) # 从当前位置偏移5个字节
print(f.tell()) # 5
print(f.readline()) # b' World!\r\n'
print(f.tell()) # 14
- json文件操作(dumps()、loads()、dump()、load()方法)
test_dict = {'Customer': {'name': 'xxx', 'age': 20}}
print(test_dict) # {'Customer': {'name': 'xxx', 'age': 20}}
print(type(test_dict)) # <class 'dict'>
# dumps() 将数据转换成字符串
json_str = json.dumps(test_dict)
print(json_str) # {"Customer": {"name": "xxx", "age": 20}}
print(type(json_str)) # <class 'str'>
# loads() 将字符串转换成dict
json_ctx = json.loads(json_str)
with open('test.json', 'w+') as f:
json.dump(json_ctx, f) # 写入
# 读取json文件
with open('test.json', 'r') as f:
print(json.load(f)) # {'Customer': {'name': 'xxx', 'age': 20}}