I am trying to read this text file and display its data. I should report product name, its value & most valuable product. I added at the end what I have tried doing so far:
Here is how the text file looks like:
item name 1 ex: hats
quantity of item 1 ex: 12
unit price of item 1 ex: 5.9
item name 2 ex: jacket
quantity of item 2 ex: 13
unit price of item 2 ex: 29.9
Expected output
12 hats at 5.9 the unit. total value: 70.8
13 jackets at 29.9 the unit. total value: 390
total inventory value: 460.8
most valuable inventory: jacket: 390
what I've tried doing so far:
filename = "store.txt"
with open(filename) as f:
content = f.read().splitlines()
content_list = [content[i * 3:(i + 1) * 3] for i in range((len(content) + 3 - 1) // 3)]
total_value = 0
for items in content_list:
value = float(items[2])*(float(items[1]))
print(items[1],'', items[0], '@ $', items[2], '. Value: $', value)
total_value += value
#max_value = max(value)
print('')
print('total value: '+ str(total_value))
#print('Highest value item: ' + str(max_value))
getting a particular thing sliced from the text file you can use
python re package
link if want to understand more about this package
re.split(pattern, string, flags=0)
this will return a list
lis = [my_list[i * n:(i + 1) * n] for i in range((len(my_list) + n - 1) // n )]
n=size you want to break them in
my_list=the list you want to break
file = open("store.txt")
lis=[]
for line in file:
if(line.startswith("item")):
item_name=line[line.find(":")+1:]
lis.append(item_name.strip())
elif(line.startswith("quantity")):
quantity=line[line.find(":")+1:]
lis.append(float(quantity))
elif(line.startswith("unit")):
unit=line[line.find(":")+1:]
lis.append(float(unit))
content_list = [lis[i * 3:(i + 1) * 3] for i in range((len(lis) + 3 - 1) // 3)]
print(content_list)
total_value=0
lis2=[]
for items in content_list:
value = (items[2])*(items[1])
print(items[1],'', items[0], '@ $', items[2], '. Value: $', value)
lis2.append(value)
total_value+=value
max_value = max(lis2)
print('')
print('total value: '+ str(total_value))
print('Highest value item: ' + str(max_value))