¿La forma más fácil de conservar una estructura de datos en un archivo en Python?


Digamos que tengo algo como esto:

d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] }

¿Cuál es la forma más fácil de progamáticamente meter eso en un archivo que pueda cargar desde python más tarde?

¿Puedo de alguna manera guardarlo como fuente python (desde dentro de un script python, no manualmente!), entonces import más tarde?

¿O debería usar JSON o algo así?

Author: Blorgbeard, 2009-06-26

7 answers

Utilice el módulo pickle.

import pickle
d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] }
afile = open(r'C:\d.pkl', 'wb')
pickle.dump(d, afile)
afile.close()

#reload object from file
file2 = open(r'C:\d.pkl', 'rb')
new_d = pickle.load(file2)
file2.close()

#print dictionary object loaded from file
print new_d
 53
Author: ecounysis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-26 06:04:57

Elige: Biblioteca Estándar de Python - Persistencia de datos. Cuál es el más apropiado puede variar según cuáles sean sus necesidades específicas.

pickle es probablemente el más simple y más capaz en cuanto a "escribir un objeto arbitrario a un archivo y recuperarlo" va-puede manejar automáticamente clases personalizadas y referencias circulares.

Para obtener el mejor rendimiento de decapado (velocidad y espacio), utilice cPickle en HIGHEST_PROTOCOL.

 12
Author: Miles,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-26 04:34:46

Pruebe el módulo shelve que le dará un diccionario persistente, por ejemplo:

import shelve
d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] }

shelf = shelve.open('shelf_file')
for key in d:
    shelf[key] = d[key]

shelf.close()

....

# reopen the shelf
shelf = shelve.open('shelf_file')
print(shelf) # => {'qwerty': [4, 5, 6], 'abc': [1, 2, 3]}
 7
Author: mhawke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-29 22:37:02

JSON tiene fallas, pero cuando satisface sus necesidades, también es:

  • fácil de usar
  • incluido en la biblioteca estándar como el json módulo
  • interfaz algo similar a pickle, que puede manejar situaciones más complejas
  • texto editable por humanos para depuración, uso compartido y control de versiones
  • código Python válido
  • bien establecido en la web (si su programa toca cualquiera de ese dominio)
 4
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-26 05:07:48

También es posible que desee echar un vistazo a La base de datos de objetos de Zope el más complejo que se obtiene:-) Probablemente exceso de lo que tiene, pero se escala bien y no es demasiado difícil de usar.

 4
Author: Jay Atkinson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-13 18:20:40

Si desea guardarlo en un formato similar a JSON fácil de leer, use repr para serializar el objeto y eval para deserializarlo.

repr(object) -> string

Devuelve la representación de cadena canónica del objeto. Para la mayoría de los tipos de objetos, eval(repr(object)) == object.

 3
Author: John Kugelman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-26 04:31:53

Solo para agregar a las sugerencias anteriores, si desea que el formato de archivo sea fácilmente legible y modificable, también puede usar YAML. Funciona extremadamente bien para dictos y listas anidadas, pero también escala para estructuras de datos más complejas (es decir, aquellas que involucran objetos personalizados), y su gran ventaja es que el formato es legible.

 2
Author: Eli Bendersky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-26 04:45:57