前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python笔记(五):异常处理和数据存储

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

作者头像
free赖权华
发布2018-04-27 16:07:53
6200
发布2018-04-27 16:07:53
举报
文章被收录于专栏:赖权华的笔记赖权华的笔记

注:和上一篇有关联

(一)  finally 和 输出异常信息

代码语言:javascript
复制
try:

      the_man = open(r'C:\Users\123456\Desktop\test.txt')

      print(the_man.readline(),end="")

except IOError as err:

    #输出异常信息

    print("异常信息:"+ str(err))
代码语言:javascript
复制
#str()转换为字符串

finally:

    #不管是否发生异常一定会执行

    the_man.close()

(二)  使用 with

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

代码语言:javascript
复制
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会自动去关闭文件。

代码语言:javascript
复制
try:

    with open('test.txt') as the_man:

      print(the_man.readline(),end="")

except IOError as err:

    #输出异常信息

    print("异常信息:"+ str(err))

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

代码语言:javascript
复制
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))

(四)  将数据长期存储

代码语言:javascript
复制
通过pickle 实现,代码如下。
代码语言:javascript
复制
import pickle
代码语言:javascript
复制
man = [1,2,3]
代码语言:javascript
复制
with open('the_man.pickle','wb') as saveman:

    pickle.dump(man,saveman)

    #保存数据
代码语言:javascript
复制
with open('the_man.pickle','rb') as resman:

    man = pickle.load(resman)

    #需要时恢复数据

print(man)

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

(1)   处理文件代码

代码语言:javascript
复制
from FirstPython import the_list as tl
代码语言:javascript
复制
#导入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笔记(二)中做过说明,这里做了一点修改)

代码语言:javascript
复制
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="")
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-01-31 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档