在文本文件中找到变量后如何读取下一行?

问题描述 投票:0回答:1

我正在尝试为电动汽车驾驶员制作一个应用程序,我正在使用一个文本文件来存储数据,它的工作方式是我有电动汽车的名称,名称下的行包含它可以获得的里程每 1%,我已经得到它,所以它可以找到特定的汽车,但我无法使用该数字找到车辆的范围。

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

这就是我所拥有的,但每次它找到汽车时都找不到它后面的范围。

python text-files read-write
1个回答
0
投票

一旦调用 cars.read(),它会将文件的全部内容读取到 car 中,因此 cars.readline() 就没有任何内容可以读取了。

您需要逐行读取文件。如果该行有汽车名称,则阅读下一行的英里数。

with open('cars.txt', 'r') as cars:
check = input("Enter full name of car: ")
found = False
for line in cars:
    if check in line.strip():
        found = True
        miles_per_percent = float(cars.readline().strip())
        total_range = miles_per_percent * 100
        print(f"Found {check} with a range of {total_range} miles at 100% charge.")
        break

来源:我的文章https://ioflood.com/blog/python-read-file-line-by-line/

© www.soinside.com 2019 - 2024. All rights reserved.