记录Python中关于异常、文件读取、序列化的相关知识点。
异常
python中对于错误的处理,也采用了异常
的处理机制。
举例
try:
print('try...')
r = 10/0
print('result:',r)
except ZeroDivisionError as e:
print('except:',e)
finally:
print('finally...')
print('End')
输出结果:
try...
except: division by zero
finally...
End
从结果可以看出,把有有可能出现错的代码段放在try
程序段中,如果出现错误(异常)。程序不再执行接下类的语句,而是直接跳转到except
程序段中进行异常处理。之后再执行finallty
程序段中的程序。
文件
python 提供了对于磁盘的IO读写功能
文件读取
f = open('C:\\Users\\hh\\Documents\\PythonWorks\\test.txt','r')
print(f.read())
f.close
当文件不存在的时候回报错,所以可以用异常去捕获
try:
f = open('C:\\Users\\hh\\Documents\\PythonWorks\\test.txt','r')
print(f.read())
finally:
if f:
f.close()
python 提供了简便写法
with open('C:\\Users\\hh\\Documents\\PythonWorks\\test.txt','r')as f:
print(f.read())
无需用try
语句,也无需主动关闭文件。
如果需要读取二进制文件(图片,音频)。可以把r
变为rb
。如果读取其他编码的文件,可以传入encoding 参数
。
文件写入
with open('C:\\Users\\hh\\Documents\\PythonWorks\\test.txt', 'w') as f:
f.write('Hello, world!')
格式化
程序运行的时候变量都是存储在内存中的,为了方便数据的存储和在网络上的传输。提出课序列化的处理方式
序列化 反序列化
import pickle
d=dict(name = 'hh',age = 20,score = 90)
with open('C:\\Users\\hh\\Documents\\PythonWorks\\test.txt', 'wb') as f:
pickle.dump(d,f)
with open('C:\\Users\\hh\\Documents\\PythonWorks\\test.txt', 'rb') as f:
d2 = pickle.load(f)
print(d2)
把一个dict序列化后存在磁盘上,然后在读回,反序列化后打印。