Ich bin es gewohnt, Daten mithilfe von CSV-Dateien in Python=============================================================================== Eine Json- oder Pck-Datei? Zum Beispiel:
data = {}
data ['key1'] = "keyinfo"
data ['key2'] = "keyinfo2"
Ich würde gerne wissen, wie man das speichert und wie man es dann wieder lädt.
Pickle speichern:
try:
import cPickle as pickle
except ImportError: # python 3.x
import pickle
with open('data.p', 'wb') as fp:
pickle.dump(data, fp, protocol=pickle.HIGHEST_PROTOCOL)
Weitere Informationen zum Argument protocol
finden Sie in Dokumentation zum Beizmodul .
Pickle load:
with open('data.p', 'rb') as fp:
data = pickle.load(fp)
JSON save:
import json
with open('data.json', 'w') as fp:
json.dump(data, fp)
Geben Sie zusätzliche Argumente wie sort_keys
Oder indent
ein, um ein hübsches Ergebnis zu erhalten. Das Argument sort_keys sortiert die Schlüssel alphabetisch und indent rückt Ihre Datenstruktur mit indent=N
Leerzeichen ein.
json.dump(data, fp, sort_keys=True, indent=4)
JSON load:
with open('data.json', 'r') as fp:
data = json.load(fp)
Minimales Beispiel, direkt in eine Datei schreiben:
import json
json.dump(data, open(filename, 'wb'))
data = json.load(open(filename))
oder sicher öffnen/schließen:
import json
with open(filename, 'wb') as outfile:
json.dump(data, outfile)
with open(filename) as infile:
data = json.load(infile)
Wenn Sie es in einer Zeichenfolge anstelle einer Datei speichern möchten:
import json
json_str = json.dumps(data)
data = json.loads(json_str)
Siehe auch das beschleunigte Paket ujson. https://pypi.python.org/pypi/ujson
import ujson
with open('data.json', 'wb') as fp:
ujson.dump(data, fp)
Wenn Sie nach der Serialisierung keine Daten in anderen Programmen benötigen, empfehle ich dringend das Modul shelve
. Stellen Sie es sich als dauerhaftes Wörterbuch vor.
myData = shelve.open('/path/to/file')
# check for values.
keyVar in myData
# set values
myData[anotherKey] = someValue
# save the data for future use.
myData.close()
So schreiben Sie in eine Datei:
import json
myfile.write(json.dumps(mydict))
So lesen Sie aus einer Datei:
import json
mydict = json.loads(myfile.read())
myfile
ist das Dateiobjekt für die Datei, in der Sie das Diktat gespeichert haben.
Wenn Sie eine Alternative zu pickle
oder json
suchen, können Sie klepto
verwenden.
>>> 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}
Mit klepto
, wenn Sie serialized=True
, das Wörterbuch wäre geschrieben worden nach memo.pkl
als eingelegtes Wörterbuch statt mit Klartext.
Sie können klepto
hier abrufen: https://github.com/uqfoundation/klepto
dill
ist wahrscheinlich die bessere Wahl zum Beizen als pickle
selbst, da dill
fast alles in Python serialisieren kann. klepto
kann auch dill
verwenden.
Sie können dill
hier abrufen: https://github.com/uqfoundation/dill
Das zusätzliche Hokuspokus in den ersten Zeilen ist, dass klepto
so konfiguriert werden kann, dass Wörterbücher in einer Datei, in einem Verzeichniskontext oder in einer SQL-Datenbank gespeichert werden. Die API ist für alles, was Sie als Backend-Archiv auswählen, dieselbe. Es gibt Ihnen ein "archivierbares" Wörterbuch, mit dem Sie load
und dump
verwenden können, um mit dem Archiv zu interagieren.
Dies ist ein altes Thema, aber der Vollständigkeit halber sollten wir ConfigParser und configparser, die Teil der Standardbibliothek sind, in Python 2 bzw. 3. Dieses Modul liest und schreibt in eine config/ini file and (zumindest in Python 3)) verhält sich in vielerlei Hinsicht wie ein Wörterbuch. Es hat den zusätzlichen Vorteil, dass Sie mehrere Wörterbücher in separaten Abschnitten Ihrer config/ini-Datei speichern und abrufen können sie. Süß!
Python 2.7.x Beispiel.
import ConfigParser
config = ConfigParser.ConfigParser()
dict1 = {'key1':'keyinfo', 'key2':'keyinfo2'}
dict2 = {'k1':'hot', 'k2':'cross', 'k3':'buns'}
dict3 = {'x':1, 'y':2, 'z':3}
# make each dictionary a separate section in config
config.add_section('dict1')
for key in dict1.keys():
config.set('dict1', key, dict1[key])
config.add_section('dict2')
for key in dict2.keys():
config.set('dict2', key, dict2[key])
config.add_section('dict3')
for key in dict3.keys():
config.set('dict3', key, dict3[key])
# save config to file
f = open('config.ini', 'w')
config.write(f)
f.close()
# read config from file
config2 = ConfigParser.ConfigParser()
config2.read('config.ini')
dictA = {}
for item in config2.items('dict1'):
dictA[item[0]] = item[1]
dictB = {}
for item in config2.items('dict2'):
dictB[item[0]] = item[1]
dictC = {}
for item in config2.items('dict3'):
dictC[item[0]] = item[1]
print(dictA)
print(dictB)
print(dictC)
Python 3.X Beispiel.
import configparser
config = configparser.ConfigParser()
dict1 = {'key1':'keyinfo', 'key2':'keyinfo2'}
dict2 = {'k1':'hot', 'k2':'cross', 'k3':'buns'}
dict3 = {'x':1, 'y':2, 'z':3}
# make each dictionary a separate section in config
config['dict1'] = dict1
config['dict2'] = dict2
config['dict3'] = dict3
# save config to file
f = open('config.ini', 'w')
config.write(f)
f.close()
# read config from file
config2 = configparser.ConfigParser()
config2.read('config.ini')
# ConfigParser objects are a lot like dictionaries, but if you really
# want a dictionary you can ask it to convert a section to a dictionary
dictA = dict(config2['dict1'] )
dictB = dict(config2['dict2'] )
dictC = dict(config2['dict3'])
print(dictA)
print(dictB)
print(dictC)
konsolenausgabe
{'key2': 'keyinfo2', 'key1': 'keyinfo'}
{'k1': 'hot', 'k2': 'cross', 'k3': 'buns'}
{'z': '3', 'y': '2', 'x': '1'}
inhalt der config.ini
[dict1]
key2 = keyinfo2
key1 = keyinfo
[dict2]
k1 = hot
k2 = cross
k3 = buns
[dict3]
z = 3
y = 2
x = 1
Wenn Sie in einer JSON-Datei speichern, ist dies die beste und einfachste Methode:
import json
with open("file.json", "wb") as f:
f.write(json.dumps(dict).encode("utf-8"))