Python笔记(五):异常处理和数据存储

栏目: Python · 发布时间: 8年前

内容简介:Python笔记(五):异常处理和数据存储

注:和上一篇有关联

(一)  finally 和 输出异常信息

try:
the_man = open(r'C:\Users\123456\Desktop\test.txt')
print(the_man.readline(),end="")
except IOError as err:
#输出异常信息
print("异常信息:"+ str(err))
#str()转换为字符串
finally:
#不管是否发生异常一定会执行
the_man.close()

(二)  使用 with

(1)   上面的代码如果文件不存在,就不会创建the_man对象,那么执行the_man.close()就会出现NameError错误,所以得先判断是否存在文件 test.txt是否存在

try:
the_man = open('test.txt')
print(the_man.readline(),end="")
except IOError as err:
#输出异常信息
print("异常信息:"+ str(err))
finally:
#不管是否发生异常一定会执行
if 'test.txt' in os.listdir():
#判断当前工作目录是否存在 test.txt 文件,存在时才关闭文件
the_man.close()

(2)   用(1)中的比较麻烦,可以使用with替代,下面的代码等价上面的代码。使用with时,PYTHON会自动去关闭文件。

try:
with open('test.txt') as the_man:
print(the_man.readline(),end="")
except IOError as err:
#输出异常信息
print("异常信息:"+ str(err))

(三)  通过open(),将数据写入文件。

man = [1,2,3]
try:
with open('test.txt','w') as the_man:
print(man,file=the_man)
#man是要写入的数据, file= 是要写入的文件对象
except IOError as err:
#输出异常信息
print("异常信息:"+ str(err))

(四)  将数据长期存储

通过pickle 实现,代码如下。
<strong>import </strong>pickle
man = [1,2,3]
with open('the_man.pickle','wb') as saveman:
pickle.dump(man,saveman)
#保存数据
with open('the_man.pickle','rb') as resman:
man = pickle.load(resman)
#需要时恢复数据
print(man)

(五)  接上篇(笔记4),判断话是张三还是李四说的,分别添加到不同的列表,并存储到zs.txt和ls.txt中。

(1)   处理文件代码

<strong>from </strong>FirstPython <strong>import </strong>the_list <strong>as </strong>tl
#导入the_list模块
zs = []
ls = []
ww = []
try:
with open(r'C:\Users\123456\Desktop\测试.txt',encoding='UTF-8') as the_file:
for each_line in the_file:
try:
(role,line_spoken) = each_line.split(":",1)
if role =='张三':
# 如果role==张三,将line_spoken添加到man列表
zs.append(line_spoken)
elif role =='李四':
ls.append(line_spoken)
elif role == '王五':
ww.append(line_spoken)
except ValueError:
# 出现ValueError时,直接输出 each_line的值
print(each_line,end="")
the_file.close()
except IOError:
#找不到文件时提示文件不存在
print("文件不存在!")
try:
with open(r'C:\Users\123456\Desktop\zs.txt','w') as the_man:
tl.dslist(zs,the_man)
#调用dslist方法处理列表数据
with open(r'C:\Users\123456\Desktop\ls.txt','w') as the_other:
tl.dslist(ls,the_other)
# 调用dslist方法处理列表数据
except IOError:
print("文件不存在!")

(2)   处理列表数据的函数,模块名:the_list(Python笔记(二)中做过说明,这里做了一点修改)

def dslist(the_list,the_file):
#the_list:要处理的列表数据
#the_file:要写入的文件对象
for each_line in the_list:
if isinstance(each_line,list):
#数据类型是否为列表
dslist(each_line,the_file)
else:
print(each_line,file=the_file,end="")

以上所述就是小编给大家介绍的《Python笔记(五):异常处理和数据存储》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

Dreamweaver CS3 Bible

Dreamweaver CS3 Bible

Joseph W. Lowery / Wiley / May 21, 2007 / $49.99

Book Description Learn to create dynamic, data-driven Web sites using the exciting enhancements in the Dreamweaver CS3 version. You get a thorough understanding of the basics and then progress to l......一起来看看 《Dreamweaver CS3 Bible》 这本书的介绍吧!

SHA 加密
SHA 加密

SHA 加密工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具