异常的传播
#异常的传播,如果异常不被处理,就会一直传播
def a():
print(abc)
def b():
a()
def c():
b()
def d():
c()
d() #源头异常加上4次调用,共五次异常
运行结果:
def a():
print(abc)
def b():
a()
def c():
b()
def d():
c()
try:
d() #源头异常加上4次调用,共五次异常
except:
print('出现错误')
运行结果:
异常的处理
try:
print(a)
except Exception as e: #此语句,可以反映出错误的类型
print('错误便会调用此处', e, type(e))
运行结果:
异常对象的完整写法
#try语句的完整写法,try是必须的,else是可有可无的,except和finally至少有一个
try:
a = 123
print(a)
print(1/0)
except NameError as e: #捕捉错误类型,对应执行,except语句只会执行其中之一
print('错误便会调用此处之', e)
except ZeroDivisionError as e:
print('错误便会调用此处之', e)
else: #与try同步执行,try之下的语句没问题,执行时,else之下的语句会一同执行,否则不执行
print('运行正常')
finally: #无论之前的语句怎么样,finally之下的语句都会执行
print('不管怎样,我都执行')
运行结果:
文件的打开、读取、关闭
#文件的打开
fiLe_name = '../text1.txt' #默认从当前文件夹寻找,其他位置需要设置路径
file_obj = open(fiLe_name)
print(file_obj)
运行结果:
#文件的读取及关闭
fiLe_name = '../text1.txt'
file_obj = open(fiLe_name)
read1 = file_obj.read()
print(read1)
file_obj.close() #关闭文档
file_obj.read() #第二次读取
运行结果:
#自动关闭 with...as
fiLe_name = '../text1.txt'
try: #通常情况下打开、读取文件容易出现错误,所以用try语句
with open(fiLe_name) as f:
print(f.read())
except FileNotFoundError as e:
print('文件不存在', e, type(e))
print(f.read()) #在with...as之外读取失败,证明此处已关闭
运行结果:
try:
with open('../text2.txt') as f1:
print(f1.read())
except FileNotFoundError as e:
print('文件不存在', e, type(e))
运行结果:
多种读取方式
file_name = '../text1.txt'
try:
with open(file_name, encoding='utf-8') as f:
print(f.read(6)) #读取6个字符
print(f.read(6)) #再读取6个字符
print(f.readline()) #再读取一行
print(f.readline()) #再读取一行
print(f.readlines()) #读取多行
print(f.readlines()) #[] 读取完了,没数据了,显示为空
except Exception as e:
print('文件不存在', e, type(e))
运行结果:
文件的写入
#文件的写入
file_name = '../text1.txt'
try:
with open(file_name, 'w', encoding='utf-8') as f: #默认的模式是‘r’,写入时需改为‘w’,即是write
f.write('落霞与孤鹜齐飞,秋水共长天一色') #write写入的时候的特性是会覆盖原内容
f.write(str(12345)) #write的另一个写入特性,只可写入str类型
except Exception as e:
print('文件不存在', e, type(e))
运行结果:
#文件的写入,增加而不覆盖的情况
file_name = '../text1.txt'
try:
with open(file_name, 'a', encoding='utf-8') as f: #模式改成'a',即add
f.write('\n 有朋自远方来,不亦说乎')
except Exception as e:
print('文件不存在', e, type(e))
运行结果:
二进制文件的写入
#二进制文件的写入
file_name = r'C:\Users\Administrator\Desktop\新裤子 - 没有理想的人不伤心.mp3'
try:
with open(file_name, 'rb') as f:
print(f.read(100))
except Exception as e:
print('文件不存在', e, type(e))
运行结果:
写入:
#二进制文件的写入
file_name = r'C:\Users\Administrator\Desktop\新裤子 - 没有理想的人不伤心.mp3' #长链接,二进制文件前加r
try:
with open(file_name, 'rb') as f: #模式改为‘rb’
new_file = 'copy newpants band.mp3'
with open(new_file, 'wb') as fnew: #对应写入模式为‘wb’
while True: #while True 循环
xone = f.read(1024*100) #每次读取1024*100个byte
if not xone: #当xone读取完,xone为空时
break #停止循环
fnew.write(xone) #写入xone
except Exception as e:
print('文件不存在', e, type(e))
运行结果: