Reputation: 141
Sorry for bothering, I am currently doing my foundation programming project and I wonder if we can get specific value from text file. For example:
When I search "Product A":
Txt File: $ amount
Product A: 30 x 20
Product B: 27 x 10
Product C: 24 x 5
Product D: 21 x 80
Product A: 30 x 50
It will shows me (expected result):
Product A = 70 #amount
Total= $450 #price*amount
Upvotes: 0
Views: 827
Reputation: 910
Below is the required code.
file1 = open('data.txt', 'r')
Lines = file1.readlines()
my_dictionary = {}
product = input("Enter the product you want to search: e.g. A, B, C, D :\t").upper()
for line in Lines: # Reading file line by line
line = line.split() # spliting the line: ['Product', 'A:', '30', 'x', '20']
if line[1].strip(':') == product:
cost = int(line[2]) # Getting the cost of product
if line[1].strip(':') in my_dictionary: # Checking if product already exists
my_dictionary[line[1].strip(':')] = my_dictionary[line[1].strip(':')] + int(line[2]) * int(line[4])
else: # Adding new product to my_dictionary
my_dictionary[line[1].strip(':')] = int(line[2]) * int(line[4])
try: # Checking of the input product is valid
print("Product", product, " = ", int(my_dictionary[product]/cost))
print("Total =", my_dictionary[product])
except: # Handling all invalid cases
print("Product not found!")
"""
data.txt file -
Product A: 30 x 20
Product B: 27 x 10
Product C: 24 x 5
Product D: 21 x 80
Product A: 30 x 50
OUTPUT -
Enter the product you want to search: e.g. A, B, C, D : a
Product A = 70
Total = 2100
Enter the product you want to search: e.g. A, B, C, D : b
Product B = 10
Total = 270
Enter the product you want to search: e.g. A, B, C, D : c
Product C = 5
Total = 120
Enter the product you want to search: e.g. A, B, C, D : d
Product D = 80
Total = 1680
Enter the product you want to search: e.g. A, B, C, D : e
Product not found!
"""
Upvotes: 1