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

注:和上一篇有关联

(一)  finally 和 输出异常信息

try:
      the_man = open(r'C:Users123456Desktop est.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 实现,代码如下。
import 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)   处理文件代码

from FirstPython import the_list as tl
#导入the_list模块
zs = []
ls = []
ww = []
try:
 with open(r'C:Users123456Desktop测试.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:Users123456Desktopzs.txt','w') as the_man:
     tl.dslist(zs,the_man)
     #调用dslist方法处理列表数据
 
with open(r'C:Users123456Desktopls.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="")
原文地址:https://www.cnblogs.com/simple-free/p/8393231.html