小编典典

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

python

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

好的,因此我对另一个问题提出了一些建议,我被告知要使用咸菜将字典保存到文件中。

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

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

泡菜将其保存到文件中时…这是格式

(dp0
S'Test'
p1
S'Test1'
p2
sS'Test2'
p3
S'Test2'
p4
sS'Starspy'
p5
S'SHSN4N'
p6
s.

您能给我一种将字符串保存到文件的替代方法吗?

这是我想要保存的格式

成员= {‘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")

阅读 130

收藏
2020-12-20

共1个答案

小编典典

当今,最常见的序列化格式是JSON,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'}
2020-12-20