Skip to main content
 首页 » 编程设计

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

2024年11月01日10qq号

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

请您参考如下方法:

您可能想查看 Python 的 shelve模块。

A “shelf” is a persistent, dictionary-like object. The difference with “dbm” databases is that the values (not the keys!) in a shelf can be essentially arbitrary Python objects — anything that the pickle module can handle. This includes most class instances, recursive data types, and objects containing lots of shared sub-objects. The keys are ordinary strings.

直接来自文档:

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