2011-02-04 37 views
44

con risposta ho finito per andare con salamoia alla fine comunqueSalva un dizionario in un file (alternativa al pickle) in Python?

Ok, quindi con qualche consiglio su un'altra domanda ho chiesto mi è stato detto di usare salamoia per salvare un dizionario in un file.

Il dizionario che stavo cercando di salvare il file è stato

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

Quando salamoia è salvato nel file ... questo è stato il formato

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

Potete per favore mi dia un modo alternativo per salvare la stringa nel file?

Questo è il formato che vorrei per salvare in

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

codice completo:

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") 
+2

Cosa c'è che non va nel formato? Come vorresti che fosse? –

+0

Mi piacerebbe che salvi come un dizionario normale E.g. membri = {'Starspy': 'SHSN4N', 'Test': 'Test1'} – wKavey

+1

Vedere [Memorizzazione dei dizionari Python] (http://stackoverflow.com/q/7100125/562769) –

risposta

58

Certo, salvarlo come CSV:

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

Poi leggendo sarebbe:

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

Un'altra alternativa sarebbe JSON (json per la versione 2.6+, o installare simplejson per 2,5 e sotto):

>>> import json 
>>> dict = {"hello": "world"} 
>>> json.dumps(dict) 
'{"hello": "world"}' 
+0

Grazie, puoi comunque importare .csv File? – wKavey

+0

Sì, vedi la mia modifica. –

+0

Oh wow questo funziona per quanto posso dire. Grazie un pacco! – wKavey

52

Il formato di serializzazione più comune per questo al giorno d'oggi è JSON, che è universalmente supportato e rappresenta strutture di dati semplici come i dizionari molto chiaramente.

>>> 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'} 
+2

Gli do un colpo. Come posso specificare il file da cui scaricare/caricarlo? – wKavey

+9

Dump restituisce una stringa. Puoi semplicemente scrivere questo in qualsiasi file come da python normale IO 'con open ('file.json', 'w') come f: f.write (json.dumps (membri))' –

+0

che cosa è il tuo in the json formato di caricamento? –

0

Mentre io suggerirei pickle, se si vuole un'alternativa, è possibile utilizzare klepto.

>>> init = {'y': 2, 'x': 1, 'z': 3} 
>>> import klepto 
>>> cache = klepto.archives.file_archive('memo', init, serialized=False) 
>>> cache   
{'y': 2, 'x': 1, 'z': 3} 
>>> 
>>> # dump dictionary to the file 'memo.py' 
>>> cache.dump() 
>>> 
>>> # import from 'memo.py' 
>>> from memo import memo 
>>> print memo 
{'y': 2, 'x': 1, 'z': 3} 

Con klepto, se si fosse usato serialized=True, il dizionario sarebbe stato scritto memo.pkl come un dizionario in salamoia invece che con testo in chiaro.

È possibile ottenere klepto qui: https://github.com/uqfoundation/klepto

dill è probabilmente una scelta migliore per il decapaggio allora pickle stessa, come dill può serializzare quasi tutto in pitone. klepto può anche utilizzare dill.

È possibile ottenere dill qui: https://github.com/uqfoundation/dill

6

Anche se, a differenza di pp.pprint(the_dict), questo non sarà così bella, sarà correre insieme, str() almeno fa un dizionario salvabile in un modo semplice per le attività rapide:

f.write(str(the_dict)) 
+0

Da Python 3.2, questo oggetto stringa salvato può essere importato da ['ast.literal_eval'] (https://docs.python.org/3/library/ast.html#ast.literal_eval) – Chris

3

è asked

Ill dare un colpo. Come posso specificare il file da cui scaricare/caricarlo?

Oltre a scrivere in una stringa, il modulo fornisce una json -Metodo dump(), che scrive in un file:

>>> a = {'hello': 'world'} 
>>> import json 
>>> json.dump(a, file('filename.txt', 'w')) 
>>> b = json.load(file('filename.txt')) 
>>> b 
{u'hello': u'world'} 

C'è un metodo load() per la lettura, anche.