2

我正在编写一个程序,该程序接受用户输入并将其腌制到文件中。但是每次我运行 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()
4

1 回答 1

2

您可能想查看 Python 的搁置模块。

“架子”是一个持久的、类似字典的对象。与“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
于 2013-09-05T04:10:37.327 回答