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.
I'd suggest to read the file into a dictionary, then use that dictionary to find the car, e.g.:
data = []
with open("cars.txt", "r") as f_in:
for line in map(str.strip, f_in):
if line == "":
continue
data.append(line)
data = dict(zip(data[::2], data[1::2]))
name = input("Enter full name of car: ")
print(data.get(name, "Not Found"))
Prints:
Enter full name of car: Kia Niro EV
2.4
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?)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With