前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python学习(六):数据存储

python学习(六):数据存储

作者头像
烤粽子
发布2021-07-07 19:17:54
3350
发布2021-07-07 19:17:54
举报

在处理完数据后,通常是不是把这些数据都丢弃了,而是将之保存。这节学习将处理完成的数据进行保存。#sketch.txt

1.  打开文件处理后保存到新的文件中

代码语言:javascript
复制
man=[]
other=[]
try:
    data=open('sketch.txt')
    for each_line in data:
        try:
            (role,line_spoken)=each_line.split(':',1)
            line_spoken=line_spoken.strip() #strip()从字符中去除不必要的空白符
            if role=='Man':
                man.append(line_spoken)
            elif role=='Other Man':
                other.append(line_spoken)
        except ValueError:
            pass
    data.close()
except IOError:
    print('The file is missing!')

try:
    man_file=open('data_man.txt','w')    #以“写”模式打开文件
    other_file=open('data_other.txt','w') #如果这个文件不存在,程序会自动新建一个文件。如果该文件存在则会覆盖原文件
    
    print(man,file=man_file)  #file='存储文件名'
    print(other,file=other_file)
    
    man_file.close()  #要记得关闭文件
    other_file.close()
    
except IOError:
    print('file Error!')

注意:写模式下,如果原来存在目标文件,程序会擦除文件里的原有数据,再进行写入。

如果不想修改原文件,想在后面追加,可以用'a'命令

代码语言:javascript
复制
man_file=open('data_man.txt','a')

2. 文件修改

考虑到程序可能在运行过程中出现问题,导致中途崩溃一些关键性的代码得不到执行,我们对代码做一些修改。存储数据到新文件中时,需要关闭文件,若程序崩溃则文件没关闭会让数据出错。将文件关闭代码移入finally中,这些代码在最后总能执行,这样能减少数据被破坏的可能性。

代码语言:javascript
复制
try:
    man_file=open('data_man.txt','w')   
    other_file=open('data_other.txt','w') 
    
    print(man,file=man_file)  
    print(other,file=other_file)
    
except IOError:
    print('File error!')

finally:
    man_file.close()
    other_file.close()

3. with语句

代码语言:javascript
复制
try:
    with open('data_man.txt','w') as man_file:
        print(man,file=man_file)  #file='存储文件名'
    with open('data_other.txt','w') as other_file:
        print(other,file=other_file)
        
except IOError as err:
    print('File error:'+str(err))

4.

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-03-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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