I am trying to make an app for electric vehicle drivers and i'm using a text file to store the data the way it works is i have the name of the electric vehicle and the the line under the name contains the miles it can get per 1%, i've got it so it can find the specific car but i can't find the range of the vehicle using that number.
cars.txt
MG MG4 EV Long Range
2.25
BMW iX1 xDrive30
2.3
Kia Niro EV
2.4
Tesla Model Y Long Range Dual Motor
2.7
BMW i4 eDrive40
3.2
code
with open('cars.txt', 'r')as cars:
check = input("Enter full name of car: ")
car = cars.read()
percentage = cars.readline()
if check in car:
print("Found")
total = range
print(percentage)
this is what i have but every time it finds the car it won't find the range after it.
You can do the following:
target_car = "Kia Niro EV"
with open("temp.txt") as f:
for line in f:
if line.rstrip() == target_car:
range_ = float(next(f))
break
else:
range_ = "Not Found"
print(f"range is: {range_}")
f
is a consumable iterator. You iterate over it until you find your car, then the next item in that iterator is what you're looking for.
Also note that you don't store the whole file in the memory in case you're dealing with a huge file. (In that case why wouldn't you use a proper database?)