[Python实战08]使用pickle的通用IO来处理文件


通过前面我们已经知道了如何进行文件的读取和存储操作,但是我们所做的只是对某个特定的格式进行处理,不能通过上面所写代码处理所有的IO操作,而对于这个问题,python为我们提供了一个原生态的IO处理工具,即pickle引擎,它可以保存和加载几乎任何Python数据对象,包括我们现在要处理的列表。

如下图为pickle的工作示意图:

\

上面这张介绍了将数据存入到对应文件的示意图,我们可以把处理后的数据保存到磁盘上,也可以保存到数据库中,当然也可以通过网络进行传输。当另一个人接收到你传递的数据以后,当然也要通过pickle引擎把数据重新读到python的内存中,如下:

\

下面我们就通过pickle对之前的文本进行操作了,在进行操作时,我们需要导入pickle模块,并且使用dump()进行数据的保存,使用load()进行数据的读取,但是pickle要求我们进行文件操作时一定要指定以而进行操作一个文件,详细代码如下:

import pickle

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!')

try:
    with open('man_data.txt','wb') as man_file,open('other_data.txt','wb') as other_file:
        pickle.dump(man,man_file)
        pickle.dump(other,other_file)
except IOError as err:
    print('File error:'+str(err))
except pickle.PickleError as perr:
    print('pickling error:'+str(perr))
这样,我们就能把数据分别保存到man_data.txt和other_data.txt文件中了,文件的内容如下:

 

man_data.txt:


						

评论关闭