Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i read the next line after finding a variable in a text file using python?

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.

like image 499
Daily stuff And things Avatar asked Sep 08 '26 15:09

Daily stuff And things


2 Answers

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
like image 146
Andrej Kesely Avatar answered Sep 11 '26 04:09

Andrej Kesely


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?)

like image 31
SorousH Bakhtiary Avatar answered Sep 11 '26 05:09

SorousH Bakhtiary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!