使用pickle记录用户的输入而不覆盖文件

时间:2013-09-05 03:39:46

标签: python pickle

我正在编写一个程序,它接受用户输入并将其pickle到文件中。但每次我运行python脚本时它都会覆盖我指定的文件。如何开始记录最后停止的pickle信息?或者我需要用另一种方式吗?

这是我目前的代码。

1 import cPickle
2 from os import path, access, W_OK
3 from utility import Util #module contains finding file line length
4 
5 class Data_store:
6    def dump_data(self, var1, var2, fname):
7       PATH = '%s' % fname
8       
9       if path.isfile(PATH) and access(PATH, W_OK):
10          with file(fname, 'r+') as f:
11             cPickle.dump(var1, f, -1)
12             cPickle.dump(var2, f, -1)
13             f.close()
14       else:
15          output = open(fname, 'w')
16          cPickle.dump(var1, output, -1)
17          cPickle.dump(var2, output, -1)
18          output.close()

19    def load_data(self, fname):
20       obj = Util()
21       lnum = obj.file_len(fname)
22       with open(fname, 'r') as f:
23         #output = open(fname, 'r')
24          for i in range(0, lnum+1):
25             data = cPickle.load(f)
26             print data 
27       f.close()

1 个答案:

答案 0 :(得分:2)

您可能需要查看Python的shelve模块。

  

“架子”是一个持久的,类似字典的对象。与“dbm”数据库的区别在于,架子中的值(而不是键!)可以是基本上任意的Python对象 - pickle模块可以处理的任何内容。这包括大多数类实例,递归数据类型和包含许多共享子对象的对象。键是普通的字符串。

直接来自文档:

import shelve

d = shelve.open(filename) # open -- file may get suffix added by low-level
                          # library

d[key] = data   # store data at key (overwrites old data if
                # using an existing key)
data = d[key]   # retrieve a COPY of data at key (raise KeyError if no
                # such key)
del d[key]      # delete data stored at key (raises KeyError
                # if no such key)
flag = d.has_key(key)   # true if the key exists
klist = d.keys() # a list of all existing keys (slow!)

# as d was opened WITHOUT writeback=True, beware:
d['xx'] = range(4)  # this works as expected, but...
d['xx'].append(5)   # *this doesn't!* -- d['xx'] is STILL range(4)!

# having opened d without writeback=True, you need to code carefully:
temp = d['xx']      # extracts the copy
temp.append(5)      # mutates the copy
d['xx'] = temp      # stores the copy right back, to persist it

# or, d=shelve.open(filename,writeback=True) would let you just code
# d['xx'].append(5) and have it work as expected, BUT it would also
# consume more memory and make the d.close() operation slower.

d.close()       # close it
相关问题