如何在Python中保存和检索文件中的列表?

时间:2012-11-27 21:35:22

标签: python list data-persistence

我搜索了一种将变量保存到文件中的方法(使其可以持久用于其他计算)。

我找到了一些解决方案,例如:https://stackoverflow.com/a/899199/1846113 但是当我在列表中实现它时:

import pickle

list = [['cccc',['asd','sdad','sdadas']],['cscc',['asd','sdad','sdadas']]]
pickle.dump(list, outfile)

它给了我这个错误

 File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1370, in dump
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 224, in dump
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 600, in save_list
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 615, in _batch_appends
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 600, in save_list
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 615, in _batch_appends
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 739, in save_global
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 811, in whichmodule
TypeError: unhashable type: 'list'

任何人都知道问题是什么? 还是其他解决方案?


编辑:使用解决方案

问题是我在创建列表时出错了。 我会发布它(所以你可以笑)并避免这个愚蠢的错误: 我通过使用(丑陋的)函数处理列表的一些元素来创建列表:

def process_element(doc):
    processed_value = do_something(doc.pop())
    return [doc.pop, processed_value] 

正如你们中的一些人已经注意到的那样,我在返回输出时出错:

[doc.pop, processed_value]

我在列表中添加了一个不可清除的方法,给了我错误。 正确的版本是:

def process_element(doc):
    processed_value = do_something(doc.pop())
    return [doc.pop(), processed_value] 

感谢。

2 个答案:

答案 0 :(得分:0)

更简单的方法是使用withforenumerate,如下所示:

with open('input.txt', 'r') as f, open('output.txt', 'w') as o:
    for numline, line in enumerate((line.split() for line in f), start=1):
        # process line elements by using line[0] line[1]...

    # When you're done, you can write results in an output file like this
    # (add a loop if needed):
    o.write("%s %s\n" % (results[0], results[1]))

Etvoilà!

答案 1 :(得分:0)

对于您的示例列表以及大多数其他人,我将使用JSON文件格式:

导入json

lst = [['cccc',['asd','sdad','sdadas']],['cscc',['asd','sdad','sdadas']]]
with open('list.json', w) as jsonout:
    json.dump(lst, jsonout)

# and then
with (open('list.json') as jsonin:
    lst = json.load(jsonin)