python持久存储

来源:互联网 发布:网络电视机顶盒哪个牌子好 编辑:程序博客网 时间:2024/05/16 08:52

注:之前写的有关python的文章都是用的python2版本,现在我发现在Headfirstpython一书中有些代码用python2运行不了,所以我又重新安装了python3….原来2和3差别还是挺大的…..其实好讨厌python的缩进…这个真的很不好呢….
1、以写模式打开文件
使用open()BIF打开磁盘文件时,可以指定使用什么访问模式,默认地,open()使用模式r表示读,所以不需要专门指定r模式。要打开一个文件完成写,需要使用w模式:
out=open(‘data.out’,’w’)
out:数据文件对象
data.out:所写文件的文件名
w:要使用的访问模式
默认地,print()BIF显示数据时会使用标准输出(通常是屏幕)。要把数据写至一个文件,需要使用file参数来指定所使用的文件对象:
print(‘hello hahahha’,file=out)
完成工作后,一定要关闭文件,确保所有数据都写至磁盘。这成为刷新输出(flushing),这一点非常重要:
out.close()
注:使用访问模式w时,python会打开指定的文件夹来完成写。如果这个文件夹已经存在,则会清除它现在所有的内容,也就是完全清除。要追加到一个文件,需要使用访问模式a。要打开一个文件完成写和读(不清除),需要使用w+。如果想要打开一个文件完成写,但是这个文件不存在,那么首先会为你创建一个文件,然后再打开文件进行写。

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()            if role=='Man':                man.append(line_spoken)            elif role=='Other Man':                other.append(line_spoken)        except ValueError:            pass    data.close()    except  IOError:    print ('The datafile is missing!')print(man)print(other)try:    man_file=open('man_data.txt','w')    other_file=open('other_data.txt','w')    print(man,file=man_file)    print(other,file=other_file)    man_file.close()    other_file.close()except IOError:    print('File error!')

2、用finally扩展try

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()            if role=='Man':                man.append(line_spoken)            elif role=='Other Man':                other.append(line_spoken)        except ValueError:            pass    data.close()    except  IOError:    print ('The datafile is missing!')print(man)print(other)try:    man_file=open('man_data.txt','w')    other_file=open('other_data.txt','w')    print(man,file=man_file)    print(other,file=other_file)except IOError as err:    print('File error:'+srt(err))finally:    man_file.close()    other_file.close()

3、知道错误类型还不够
下面试图打开一个不存在的文件

import osos.chdir(r'C:\Users\Administrator\Desktop\HeadFirstPython\chapter3')try: data=open('missing.txt') print(data.readline(),end='')except IOError as err:    print('File error:'+str(err))finally:    if 'data' in locals()://如果不加上这句会提示data找不到     data.close()

4、用with处理文件
由于处理文件时try/except/finally模式非常常用,所以python提供了一个语句来抽象出相关的细节。对文件使用with语句时,可以大大减少需要编写的代码量,因为有了with语句不再需要finally组来处理文件的关闭,即妥善关闭一个可能打开的数据文件。

try:    data=open('its.txt','w')    print('Hello world',file=data)except IOError as err:    print('File is error:'+str(err))finally:    if 'data' in locals():     data.close()
try:    with open('its.txt','w') as data:        print('Hello world',file=data)except  IOError as err:    print('File is error:'+str(err))

以上2段代码是等价的,使用with时,不需要操心关闭打开的文件,因为python解释器会自动为你考虑这一点。
5、实现文件换行输出

import sysdef print_lol(the_list,indent=False,level=0,fh=sys.stdout):    for each_item in the_list:        if isinstance(each_item,list):            print_lol(each_item,indent,level+1,fh)        else:            for tab_stop in range(level):                print('\t',end='',file=fh)            print(each_item,file=fh)
import nestertry:    man=[]    other=[]    with open('sketch.txt') as data:        for line in data:            if not line.find(':')==-1:                (role,spoken_line)=line.split(':',1)                spoken_line=spoken_line.strip()                if role=='Man':                 man.append(spoken_line)                elif role=='Other Man':                 other.append(spoken_line)except IOError as error:    print('File error:'+str(err))try:    with open('man_data.txt','w') as man_file:        nester.print_lol(man,fh=man_file)    with open('other_data.txt','w') as other_file:      nester.print_lol(other,fh=other_file)except  IOError as err:    print('File error:'+str(err))

6、腌制数据pickle
使用pickle很简单,只需导入所需的模块,然后使用dump()保存数据,以后某个时间使用load()恢复数据。处理腌制数据的唯一要求是,必须以2进制访问模式打开文件(wb,rb中的b代表的是2进制):
import pickle

with open(‘mydata.pickle’,’wb’) as mysavedata:
pickle.dump([1,2,’three’],mysavedata)

with open(‘mydata.pickle’,’rb’) as myrestoredata:
a_list=pickle.load([1,2,’three’],myrestoredata)
print(a_list)
腌制或者解除数据腌制时如果出问题了,pickle模块会产生一个PickleError类型的异常

'''import nester'''import pickletry:    man=[]    other=[]    with open('sketch.txt') as data:        for line in data:            if not line.find(':')==-1:                (role,spoken_line)=line.split(':',1)                spoken_line=spoken_line.strip()                if role=='Man':                 man.append(spoken_line)                elif role=='Other Man':                 other.append(spoken_line)except IOError as error:    print('File error:'+str(err))try:    with open('man_data.txt','wb') as man_file, open('other_data.txt','wb') as other_file:        '''nester.print_lol(man,fh=man_file)        nester.print_lol(other,fh=other_file)'''        pickle.dump(man,man_file)        pickle.dump(other,other_file)except  pickle.PickleError as perr:    print('Pickling error:'+str(perr))

使用pickle下载数据,然后再使用nester的print_lol输出数据

import nesterimport picklenew_man=[]try:    with open('man_data.txt','rb') as man_file:        new_man=pickle.load(man_file)except IOError as err:    print('File error:'+str(err))except pickle.PickleError as perr:    print('Pickling error:'+str(perr))nester.print_lol(new_man)

这里写图片描述

这里没有显示所有的数据,但是实际输出中确实包含所有的数据。
Bullet Points:
1、strip()方法可以从字符串中去除不想要的空白符。
2、print()BIF的file参数控制将数据发送/保存到哪里。
3、会向except组传入一个异常对象,并使用as关键字赋至一个标识符。
4、str()BIF可以用来访问任何数据对象(支持串转换)的串表示。
5、locals()BIF返回当前作用域中的变量集合。
6、in操作符用于检查成员关系。
7、with语句会自动处理所有已打开文件的关闭工作,即使出现异常也不例外,with也使用as。
8、sys.stdout是python中的标准输出(输出到屏幕),可以从标准库的sys模块访问。
9、标准库的pickle模块允许你容易高效的将python数据对象保存到磁盘以及从磁盘恢复。
10、pickle.dump()将数据保存到磁盘。pickle.load()从磁盘恢复数据。