2013-11-20 75 views
0

我需要保存字典,然後在保存字典後才能讀取字典。文件I/O Python保存並讀取

這是我和它應該工作(我認爲),但是當涉及到read_dict功能我不斷收到以下錯誤: return dict(line.split() for line in x) ValueError: dictionary update sequence element #0 has length 1; 2 is required 有什麼建議?

def save_dict(dict1):

with open('save.txt', 'w') as fh: 
    for key in dict1.keys(): 
     fh.write(key + '' + dictionary1[key] + '\n') 

def readDB():

with open('save.txt', 'r') as fh: 
    return dict(new.split() for new in fh) 

回答

0

使用空間,而不是空字符串,否則str.split將返回這是會傳遞給dict()時引發錯誤的單個項目列表。

fh.write(key + ' ' + dictionary1[key] + '\n') 

或者更好地利用字符串格式化:

for key, val in dict1.items(): 
    fh.write('{} {}\n'.format(key, val)) 

演示:

>>> s = 'k' + '' + 'v'  #WRONG 
>>> s 
'kv' 
>>> s.split()  
['kv'] 

>>> s = 'k' + ' ' + 'v' #RIGHT 
>>> s 
'k v' 
>>> s.split() 
['k', 'v'] 
+0

謝謝!簡單的錯誤。漂亮的眼睛。 – user3014014

+0

@ user3014014很高興幫助,當系統允許時隨時[接受答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235)你去。 –

+0

這是相當脆弱的。如果鍵或值有空格,它將失敗。也許使用'='作爲分隔符? – tdelaney

1

除非你真正需要的文件中的行由行列表,使用類似JSON或醃製以保存字典。這些格式處理諸如鍵名中的空格,非字符串值,非ASCII字符等。

import json 
dict1 = {'test':123} 
with open('save.txt', 'w') as fh: 
    json.dump(dict1, fh) 
with open('save.txt', 'r') as fh: 
    dict2 = json.load(fh) 
0

您可能需要使用pickle module man! 看看這個例子:

## Importing 
from pickle import dump 

## You make the dictionary 
my_dict = {'a':1 , 'b':2 , 'c':3} 

## You dump the dictionary's items to a binary (.txt file for windows) 
with open('the path you want to save','wb') as da_file: 
    dump(my_dict , da_file) 

保存該文件爲 「something0.py」

## Importing 
from pickle import load 

## You getting the data back from file 
## the variable that will get the result of load module 
## will be the same type with the variable that "dumped" 
## the items to that file! 
with open('the file path which you will get the items from' , 'rb') as da_file: 
    my_dict = load(da_file) 

## Print out the results 
from pprint import pprint 
pprint(my_dict) 

保存該文件爲 「something1.py」

現在運行具有相同的兩個模塊文件在「with」語句中, 先0然後1。 而且1將打印出與0相同的結果!

0

如前所述,你應該使用的泡菜,但作爲一種更簡單的方式

FileTowriteto = open("foo.txt", "wb") 
import pickle 
DumpingDict = {"Foo":"Foo"} 
pickle.dump(DumpingDict, FileTowriteto) 

然後,當你想讀它,你可以做到這一點

OldDict = open("foo.txt", "rb") 
OldDictRecover = pickle.load(OldDict) 

這應該工作,如果輸出是二進制運行str()函數就可以了。