try:
print(a)
1/0
except Exception as b:
print('这是我的第一个解决方案',' ', b,' ', type(b))
#运行结果#
这是我的第一个解决方案 name 'a' is not defined <class 'NameError'>
3.异常的传播
def fun():
1/0
def fun1():
fun()
def fun2():
fun1()
fun2()
#运行结果#
File "D:/PYTHON/异常的传播.py", line 20, in <module>
fun2()
File "D:/PYTHON/异常的传播.py", line 19, in fun2
fun1()
File "D:/PYTHON/异常的传播.py", line 16, in fun1
fun()
File "D:/PYTHON/异常的传播.py", line 14, in fun
1/0
ZeroDivisionError: division by zero
#practice.text内容为中文
file_name='D:\help\Tools\practice.text'
file_obj=open(file_name)
print(file_obj.read(-1)) #括号内的-1表示读取全部
#运行结果#
UnicodeDecodeError: 'gbk' codec can't decode byte 0x8c in position 14: illegal multibyte sequence
#文件内容为中文的编码方法:
file_name='D:\help\Tools\practice.text'
with open(file_name,encoding='utf-8') as f:
print(f.read(-1))
#运行结果#
北冥有鱼,
其名为鲲。
鲲之大,
不知其几千里也。
file_name='D:\help\Tools\practice.text'
with open(file_name,encoding='utf-8') as f:
# print(f.read(-1))
print(f.readline())
# print(f.readline())
# print(f.readline())#readline()方法是用一次读一行
# print(f.readline())
print(f.readlines(7))#readlines()方法是根据字节,全部读取到列表内,内容读取完后,则不能再读取,这时打印会为空
#运行结果#
北冥有鱼,
['其名为鲲。\n', '鲲之大,\n']
3.文件的写入
# w 模式是一个覆盖式写入 , 写入内容必须是字符串的数据类型
# a 模式表示追加
file_name=r'D:\help\Tools\practice.text'
with open(file_name,'a',encoding='utf-8') as f:
f.write('\n唐诗三百首') #write()方法,写入必须是字符串的数据类型
#运行后文件内容#
北冥有鱼,
其名为鲲。
鲲之大,
不知其几千里也。
唐诗三百首
4.操作二进制文件
图片文字音乐视频等都是二进制文件
file_name=r'D:\CloudMusic\Anne Sophie Versnaeyen,Gabriel Saban - Autumn Romance.mp3'
with open(file_name,'rb') as f:
file_obj='123.mp3'
with open(file_obj,'wb') as k:
while True:
content=f.read(-1)
if not content:
break
k.write(content)