-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
92 lines (80 loc) · 2.95 KB
/
main.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import sys
class Products:
product_list = []
# Constructor
def __init__(self, filename):
self.filename = filename
file = open(self.filename)
self.product_list = list(map(lambda x: x.strip(), file.readlines()))
file.close()
# Method to show all the list items
def show_list(self):
cnt = 0
for i in self.product_list:
print(cnt, i.strip())
cnt += 1
# Method to edit the item
def edit_item(self, ind, product, price):
file = open(self.filename, 'w')
item = product + ' - ' + str(price)
self.product_list[ind] = item
for i in range(len(self.product_list)):
self.product_list[i] = self.product_list[i]+'\n'
file.writelines(self.product_list)
file.close()
# Method to add a new item
def add_item(self, product, price):
file = open(self.filename, 'w')
item = product + ' - ' + str(price)
self.product_list.append(item)
for i in range(len(self.product_list)):
self.product_list[i] = self.product_list[i]+'\n'
file.writelines(self.product_list)
file.close()
# Method to delete the item
def delete_item(self, ind):
self.product_list = [
self.product_list[i]+'\n' for i in range(len(self.product_list)) if i != ind]
file = open(self.filename, 'w')
file.writelines(self.product_list)
file.close()
# Method to calculate the total price
def calc(self):
total_price = 0
for item in self.product_list:
dash = item.index('-')
total_price += float(item[dash+1:].strip())
return total_price
# Error handler for misspelled file name
try:
if len(sys.argv) != 3:
print("Missing some command line arguments")
else:
is_calc = False
# Creating the object of the class Product
products = Products(sys.argv[1])
products.show_list()
if sys.argv[2] == 'add':
is_calc = True
product = input("\nNew product name: ")
price = float(input("New product price: "))
products.add_item(product, price)
elif sys.argv[2] == 'edit':
is_calc = True
ind = int(input("\nInput the row index you want to edit: "))
product = input(f"New product name for row {ind}: ")
price = float(input(f"New product price for row {ind}: "))
products.edit_item(ind, product, price)
elif sys.argv[2] == 'delete':
is_calc = True
ind = int(
input("\nInput the index of the product you want to delete: "))
products.delete_item(ind)
elif sys.argv[2] == 'calc':
print('-' * 15)
print("Total price:", products.calc())
if is_calc:
print("\nProducts list updated successfully")
products.show_list()
except FileNotFoundError:
print("File not found")