在Python中将字典保存到文件(替代pickle)?

wKa*_*vey 48 python dictionary save pickle

回答我最后还是最后去了泡菜

好的,在另一个问题上有一些建议,我问我被告知使用pickle将字典保存到文件中.

我试图保存到文件的字典是

members = {'Starspy' : 'SHSN4N', 'Test' : 'Test1'}
Run Code Online (Sandbox Code Playgroud)

当pickle将它保存到文件中时......这就是格式

(dp0
S'Test'
p1
S'Test1'
p2
sS'Test2'
p3
S'Test2'
p4
sS'Starspy'
p5
S'SHSN4N'
p6
s.
Run Code Online (Sandbox Code Playgroud)

你能给我另一种方法将字符串保存到文件中吗?

这是我希望它保存的格式

members = {'Starspy':'SHSN4N','Test':'Test1'}

完整代码:

import sys
import shutil
import os
import pickle

tmp = os.path.isfile("members-tmp.pkl")
if tmp == True:
    os.remove("members-tmp.pkl")
shutil.copyfile("members.pkl", "members-tmp.pkl")

pkl_file = open('members-tmp.pkl', 'rb')
members = pickle.load(pkl_file)
pkl_file.close()

def show_menu():
    os.system("clear")
    print "\n","*" * 12, "MENU", "*" * 12
    print "1. List members"
    print "2. Add member"
    print "3. Delete member"
    print "99. Save"
    print "0. Abort"
    print "*" * 28, "\n"
    return input("Please make a selection: ")

def show_members(members):
    os.system("clear")
    print "\nNames", "     ", "Code"
    for keys in members.keys():
        print keys, " - ", members[keys]

def add_member(members):
    os.system("clear")
    name = raw_input("Please enter name: ")
    code = raw_input("Please enter code: ")
    members[name] = code
    output = open('members-tmp.pkl', 'wb')
    pickle.dump(members, output)
    output.close()
    return members


#with open("foo.txt", "a") as f:
#     f.write("new line\n")

running = 1

while running:
    selection = show_menu()
    if selection == 1:
        show_members(members)
        print "\n> " ,raw_input("Press enter to continue")
    elif selection == 2:
        members == add_member(members)
        print members
        print "\n> " ,raw_input("Press enter to continue")
    elif selection == 99:
        os.system("clear")
        shutil.copyfile("members-tmp.pkl", "members.pkl")
        print "Save Completed"
        print "\n> " ,raw_input("Press enter to continue")

    elif selection == 0:
        os.remove("members-tmp.pkl")
        sys.exit("Program Aborted")
    else:
        os.system("clear")
        print "That is not a valid option!"
        print "\n> " ,raw_input("Press enter to continue")
Run Code Online (Sandbox Code Playgroud)

Dav*_*ver 60

当然,将其另存为CSV:

import csv
w = csv.writer(open("output.csv", "w"))
for key, val in dict.items():
    w.writerow([key, val])
Run Code Online (Sandbox Code Playgroud)

然后阅读它将是:

import csv
dict = {}
for key, val in csv.reader(open("input.csv")):
    dict[key] = val
Run Code Online (Sandbox Code Playgroud)

另一种选择是json(json版本2.6+,或安装simplejson2.5及以下版本):

>>> import json
>>> dict = {"hello": "world"}
>>> json.dumps(dict)
'{"hello": "world"}'
Run Code Online (Sandbox Code Playgroud)

  • 这是非常正确的.但是在行间读取,OP正在寻找以人性化格式存储字符串元组......而且CVS相当不错. (4认同)
  • CSV是一个非常丑陋的建议.它用于存储数据表,通常作为电子表格的输出; 它不是用于序列化数据结构的格式. (2认同)

Gle*_*ard 53

目前最常见的序列化格式是JSON,它受到普遍支持,并且非常清楚地表示简单的数据结构,如字典.

>>> members = {'Starspy' : 'SHSN4N', 'Test' : 'Test1'}
>>> json.dumps(members)
'{"Test": "Test1", "Starspy": "SHSN4N"}'
>>> json.loads(json.dumps(members))
{u'Test': u'Test1', u'Starspy': u'SHSN4N'}
Run Code Online (Sandbox Code Playgroud)

  • 转储返回一个字符串.您可以按照普通的python IO`将其写入任何文件,使用open('file.json','w')作为f:f.write(json.dumps(members))` (10认同)
  • 我试一试.如何指定要将其转储到/加载的文件? (3认同)

小智 7

YAML格式(通过pyyaml)可能是一个很好的选择:

http://en.wikipedia.org/wiki/Yaml

http://pypi.python.org/pypi/PyYAML


gse*_*tle 7

虽然不同pp.pprint(the_dict),它不会那么漂亮,但它们会一起运行,str()至少可以让一个字典以简单的方式保存,以便快速完成任务:

f.write( str( the_dict ) )
Run Code Online (Sandbox Code Playgroud)