fork download
  1. # Persistencia (pickle, json)
  2.  
  3. import datetime as dt
  4. import pickle
  5. import json
  6.  
  7.  
  8. class DefaultEncoder(json.JSONEncoder):
  9. def default(self, o):
  10. return o.__dict__
  11.  
  12.  
  13. class Nota:
  14. def __init__(self, anyo=0, mes=0, dia=0, hora=0, contenido=""):
  15. self._anyo = anyo
  16. self._mes = mes
  17. self._dia = dia
  18. self._hora = hora
  19. self._contenido = contenido
  20.  
  21. @property
  22. def contenido(self):
  23. return self._contenido
  24.  
  25. @property
  26. def fecha(self):
  27. return dt.datetime(self._anyo,
  28. self._mes,
  29. self._dia,
  30. self._hora,
  31. 0,
  32. self.contenido)
  33.  
  34. def __str__(self):
  35. return (str(self._anyo)
  36. + "-" + str(self._mes)
  37. + "-" + str(self._dia)
  38. + " " + str(self._hora) + ":00"
  39. + " -> " + self.contenido)
  40.  
  41. @staticmethod
  42. def guarda_notas_json(fn, lnotas):
  43. with open(fn, "wt") as f:
  44. json.dump(lnotas, f, cls=DefaultEncoder)
  45.  
  46. @staticmethod
  47. def recupera_notas_json(fn):
  48. toret = []
  49.  
  50. with open(fn, "rU") as f:
  51. lnotas = json.load(f)
  52.  
  53. for d in lnotas:
  54. n = Nota()
  55. n.__dict__ = d
  56. toret.append(n)
  57.  
  58. return toret
  59.  
  60. @staticmethod
  61. def guarda_notas(fn, lnotas):
  62. with open(fn, "wb") as f:
  63. pickle.dump(lnotas, f)
  64.  
  65. @staticmethod
  66. def recupera_notas(fn):
  67. toret = []
  68. with open(fn, "rb") as f:
  69. toret = pickle.load(f)
  70.  
  71. return toret
  72.  
  73.  
  74. def guarda():
  75. nota = Nota(2018, 3, 23, 9, "Venir a clases")
  76. Nota.guarda_notas("notas.dat", [nota])
  77.  
  78.  
  79. def recupera():
  80. return Nota.recupera_notas("notas.dat")
  81.  
  82.  
  83. def guarda_json():
  84. nota = Nota(2018, 3, 23, 9, "Venir a clases")
  85. Nota.guarda_notas_json("notas_json.txt", [nota])
  86.  
  87.  
  88. def recupera_json():
  89. return Nota.recupera_notas_json("notas_json.txt")
  90.  
  91. if __name__ == "__main__":
  92. guarda_json()
  93. lnotas = recupera_json()
  94. for nota in lnotas:
  95. print(nota)
  96.  
Runtime error #stdin #stdout #stderr 0.05s 10420KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Traceback (most recent call last):
  File "./prog.py", line 92, in <module>
  File "./prog.py", line 85, in guarda_json
  File "./prog.py", line 43, in guarda_notas_json
PermissionError: [Errno 13] Permission denied: 'notas_json.txt'