Python编程与数据存储新手

2 投票
4 回答
2136 浏览
提问于 2025-04-16 19:10

我有一个关于数据存储的问题。我有一个程序,它正在创建一个对象列表。有什么好的方法可以把这些对象存储到文件中,以便程序以后可以重新加载它们呢?我试过使用Pickle,但我觉得我可能走错了方向,每次尝试读取数据时都会出现这个错误:

    Traceback (most recent call last):
     File "test.py", line 110, in <module>
knowledge = pickle.load(open("data.txt"))
    File "/sw/lib/python3.1/pickle.py", line 1356, in load
 encoding=encoding, errors=errors).load()
File "/sw/lib/python3.1/codecs.py", line 300, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
  UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 0: invalid start byte

编辑补充:这是我正在尝试的一部分代码:

FILE = open("data.txt", "rb")

knowledge = pickle.load(open("data.txt"))

FILE = open("data.txt", 'wb')

pickle.dump(knowledge, FILE)

4 个回答

0

如果你只是想稍后重新创建一些类对象,最简单的方法就是把它们的属性保存到一个文件里,然后再把这些属性读回来,根据内容来创建对象。

可以参考这个链接: http://docs.python.org/tutorial/inputoutput.html

1

没必要重写shelve,这是Python的一个对象持久化库。下面是一个例子:

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
9

我觉得问题出在这一行

knowledge = pickle.load(open("data.txt"))

没有以二进制模式打开文件。在Python 3.2中:

>>> import pickle
>>> 
>>> knowledge = {1:2, "fred": 19.3}
>>> 
>>> with open("data.txt", 'wb') as FILE:
...     pickle.dump(knowledge, FILE)
... 
>>> knowledge2 = pickle.load(open("data.txt"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/codecs.py", line 300, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 0: invalid start byte
>>> knowledge2 = pickle.load(open("data.txt","rb"))
>>> knowledge2
{1: 2, 'fred': 19.3}

撰写回答