-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path20-python-pickle-module-1.py
78 lines (62 loc) · 1.76 KB
/
20-python-pickle-module-1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
from io import open
import pickle
class Movie:
# Constructor
def __init__(self, title, time, year):
self.title = title
self.time = time
self.year = year
print('New movie has been created:', self.title)
def __str__(self):
return '{} ({})'.format(self.title, self.year)
class Catalogue:
movies = []
# Constructor
def __init__(self, movies=[]):
self.movies = movies
self.load()
def add(self, movie):
self.movies.append(movie)
self.save()
def show(self):
if len(self.movies) <= 0:
print("Empty Catalogue")
return
for movie in self.movies:
print(movie)
def load(self):
file = open('catalogue.pickle', 'ab+')
file.seek(0)
try:
self.movies = pickle.load(file)
except Exception as inst:
print(type(inst)) # the exception instance
print(inst.args) # arguments stored in .args
print(inst)
print("Empty file")
finally:
file.close()
del file
print("It has been loaded {} movies".format(len(self.movies)))
def save(self):
file = open('catalogue.pickle', 'wb')
pickle.dump(self.movies, file)
file.close()
del file
def __del__(self):
self.save() # Automatically Save
print("The file has been saved")
catalogue = Catalogue()
catalogue.show()
catalogue.add(Movie("The Godfather", 175, 1972))
catalogue.add(Movie("The Godfather II", 202, 1974))
catalogue.show()
del catalogue
catalogue = Catalogue()
catalogue.show()
catalogue.add(Movie("Toy Story", 202, 1999))
catalogue.show()
del catalogue
catalogue = Catalogue()
catalogue.show()
del catalogue