文件I / O Python保存和读取

时间:2013-11-20 19:43:02

标签: python file-io

我需要保存字典,然后能够在保存后阅读字典。

这就是我所拥有的它应该可以工作(我认为),但是当涉及到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)

4 个答案:

答案 0 :(得分:1)

除非您确实需要文件中的逐行列表,否则请使用类似json或pickle的内容来保存dict。这些格式处理键名中的空格,非字符串值,非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)

答案 1 :(得分: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']

答案 2 :(得分:0)

你可能需要使用泡菜模块男人! 看看这个例子:

## 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给文件相同的结果!

答案 3 :(得分: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()函数。