-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAssignment07.py
More file actions
297 lines (238 loc) · 9.63 KB
/
Copy pathAssignment07.py
File metadata and controls
297 lines (238 loc) · 9.63 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
#------------------------------------------#
# Title: Assignment07.py
# Desc: Working with files and exception.
# Change Log: (Who, When, What)
# DBiesinger, 2030-Jan-01, Created File
# AnhVu, 2021-Aug-12, Added Code
# AnhVu, 2021-Aug-22, Added Code for Error Handling
#------------------------------------------#
# -- DATA -- #
strChoice = '' # User input
lstTbl = [] # list of lists to hold data
dicRow = {} # list of data row
strFileName = 'CDInventory.txt' # data storage file
objFile = None # file object
# -- PROCESSING -- #
class DataProcessor:
# TODone add functions for processing here
@staticmethod
def additem (strID, strTitle, stArtist):
"""Function to add new data to the table
Args:
strID: ID number for the new record
strTitle: Title of the new record
stArtist: Artist name of the new record
Returns:
None.
"""
# TODone move processing code into function
intID = int(strID)
dicRow = {'ID': intID, 'Title': strTitle, 'Artist': stArtist}
lstTbl.append(dicRow)
@staticmethod
def removeitem (intIDDel):
"""Function to allow users to remove item from the table
Args:
intIDdel: the ID number of the record user want to delete
Returns:
None.
"""
# TODone move processing code into function
intRowNr = -1
blnCDRemoved = False
for row in lstTbl:
intRowNr += 1
if row['ID'] == intIDDel:
del lstTbl[intRowNr]
blnCDRemoved = True
break
if blnCDRemoved:
print('The CD was removed')
else:
print('Could not find this CD!')
@staticmethod
def savedata ():
"""Function to allow users to save data to the table
Args:
None.
Returns:
None.
"""
objFile = open(strFileName, 'w')
for row in lstTbl:
lstValues = list(row.values())
lstValues[0] = str(lstValues[0])
objFile.write(','.join(lstValues) + '\n')
objFile.close()
class FileProcessor:
"""Processing the data to and from text file"""
@staticmethod
def read_file(file_name, table):
"""Function to manage data ingestion from file to a list of dictionaries
Reads the data from file identified by file_name into a 2D table
(list of dicts) table one line in the file represents one dictionary row in table.
Args:
file_name (string): name of file used to read the data from
table (list of dict): 2D data structure (list of dicts) that holds the data during runtime
Returns:
None.
"""
table.clear() # this clears existing data and allows to load data from file
try:
objFile = open(file_name, 'r')
for line in objFile:
data = line.strip().split(',')
dicRow = {'ID': int(data[0]), 'Title': data[1], 'Artist': data[2]}
table.append(dicRow)
objFile.close()
except:
print ('No such file')
@staticmethod
def write_file(file_name, table):
# TODOne Add code here
# TODOne add docstring
"""Function to manage writing data from user input to file
For each row in the table, a datarow is a dictionary
Args:
file_name (string): name of file used to read the data from
table (list of dict): 2D data structure (list of dicts) that holds the data during runtime
Returns:
None.
"""
objFile = open(file_name, 'a')
for row in table:
datarow = '{}{}{}'.format (row['ID'],row['Title'],row['Artist'])
objFile.write (datarow)
objFile.close()
# -- PRESENTATION (Input/Output) -- #
class IO:
"""Handling Input / Output"""
@staticmethod
def print_menu():
"""Displays a menu of choices to the user
Args:
None.
Returns:
None.
"""
print('Menu\n\n[l] load Inventory from file\n[a] Add CD\n[i] Display Current Inventory')
print('[d] delete CD from Inventory\n[s] Save Inventory to file\n[x] exit\n')
@staticmethod
def menu_choice():
"""Gets user input for menu selection
Args:
None.
Returns:
choice (string): a lower case sting of the users input out of the choices l, a, i, d, s or x
"""
choice = ' '
while choice not in ['l', 'a', 'i', 'd', 's', 'x']:
choice = input('Which operation would you like to perform? [l, a, i, d, s or x]: ').lower().strip()
print() # Add extra space for layout
return choice
@staticmethod
def show_inventory(table):
"""Displays current inventory table
Args:
table (list of dict): 2D data structure (list of dicts) that holds the data during runtime.
Returns:
None.
"""
print('======= The Current Inventory: =======')
print('ID\tCD Title (by: Artist)\n')
for row in table:
print('{}\t{} (by:{})'.format(*row.values()))
print('======================================')
# TODOne add I/O functions as needed
@staticmethod
def userinput ():
"""Function to ask user for input of new records
Args:
None.
Returns:
id: ID number for the new record
title: Title name for new record
artist: Artist name of the new record
"""
# TODone move IO code into function
while True:
id = input('Enter ID: ').strip()
try:
intID = int(id)
title = input('What is the CD\'s title? ').strip()
artist = input('What is the Artist\'s name? ').strip()
return intID, title, artist
except:
print ('The ID you entered is not an integer')
# 1. When program starts, read in the currently saved Inventory
FileProcessor.read_file(strFileName, lstTbl)
# 2. start main loop
while True:
# 2.1 Display Menu to user and get choice
IO.print_menu()
strChoice = IO.menu_choice()
# 3. Process menu selection
# 3.1 process exit first
if strChoice == 'x':
break
# 3.2 process load inventory
if strChoice == 'l':
print('WARNING: If you continue, all unsaved data will be lost and the Inventory re-loaded from file.')
strYesNo = input('type \'yes\' to continue and reload from file. otherwise reload will be canceled')
if strYesNo.lower() == 'yes':
print('reloading...')
FileProcessor.read_file(strFileName, lstTbl)
IO.show_inventory(lstTbl)
else:
input('canceling... Inventory data NOT reloaded. Press [ENTER] to continue to the menu.')
IO.show_inventory(lstTbl)
continue # start loop back at top.
# 3.3 process add a CD
elif strChoice == 'a':
# 3.3.1 Ask user for new ID, CD Title and Artist
# TODO move IO code into function
#strID = input('Enter ID: ').strip()
#strTitle = input('What is the CD\'s title? ').strip()
#stArtist = input('What is the Artist\'s name? ').strip()
strID, strTitle, stArtist = IO.userinput()
# 3.3.2 Add item to the table
# TODO move processing code into function
#intID = int(strID)
#dicRow = {'ID': intID, 'Title': strTitle, 'Artist': stArtist}
#lstTbl.append(dicRow)
#IO.show_inventory(lstTbl)
DataProcessor.additem(strID, strTitle, stArtist)
IO.show_inventory(lstTbl)
continue # start loop back at top.
# 3.4 process display current inventory
elif strChoice == 'i':
IO.show_inventory(lstTbl)
continue # start loop back at top.
# 3.5 process delete a CD
elif strChoice == 'd':
# 3.5.1 get Userinput for which CD to delete
# 3.5.1.1 display Inventory to user
IO.show_inventory(lstTbl)
# 3.5.1.2 ask user which ID to remove
intIDDel = int(input('Which ID would you like to delete? ').strip())
# 3.5.2 search thru table and delete CD
# TODOne move processing code into function
DataProcessor.removeitem (intIDDel)
IO.show_inventory(lstTbl)
continue # start loop back at top.
# 3.6 process save inventory to file
elif strChoice == 's':
# 3.6.1 Display current inventory and ask user for confirmation to save
IO.show_inventory(lstTbl)
strYesNo = input('Save this inventory to file? [y/n] ').strip().lower()
# 3.6.2 Process choice
if strYesNo == 'y':
# 3.6.2.1 save data
# TODOne move processing code into function
DataProcessor.savedata ()
else:
input('The inventory was NOT saved to file. Press [ENTER] to return to the menu.')
continue # start loop back at top.
# 3.7 catch-all should not be possible, as user choice gets vetted in IO, but to be save:
else:
print('General Error')