Home > Software design >  How to find last value of a List in file.txt if first value match the entered data
How to find last value of a List in file.txt if first value match the entered data

Time:11-05

I am writing a simple car rental system to check price of a car.

This is the Available Vehicles.txt In which the 3rd row is the car price.

RegNumber | Car Name | Price | Transmission Type
H4E-11,Toyota,66,Automatic Transmission
X11-11,Volkswagen,62,Automatic Transmission
JBA-123,Ibiza,65,Automatic Transmission
MDZ-A1A,Kodiaq,71,Automatic Transmission

I want to loop through the first row and if the registration number matches the entered registration number it goes through the line and checks the price in the third column

I have a function that asks user to enter his/her car registration number it then checks if the registration number is available in the first row of a file.

def returnCar():
    # Ask registration number of car to rent
        regNumber = str(input("Please enter Registration Number of Car: "))

 # Check if Car is  in the system

        regNumbers = []  # List of registration number [H4E-11, X11-11, JBA-123, MDZ-A1A]

        with open("../AvailableVehicles.txt", "r", encoding="utf-8") as f:
                for data in f:
                        regRow = str(data.split(",")[0])
                        regNumbers  = [regRow]   # append registration number to the list
        if regNumber in regNumbers:
                # get price from equivalent row
            

I want to print something like:

Please enter Registration Number of Car: H4E-11
The price is: 66 dollars

CodePudding user response:

Don't parse manually csv files, use the csv module:

import csv

regNumber = input("Please enter Registration Number of Car: ")

with open('AvailableVehicles.txt') as f:
    # load file lazily
    data = csv.reader(f)

    # let's use a generator to stop on the first match
    price = next((row[2] for row in data if row[0] == regNumber), None)
    if price:
        print(f'The price is: {price}')
    else:
        print(f'Registration number not found')

Alternative using pandas, an advantage would be to compute once the prices to be able to map any registration number repeatedly without parsing the file again:

import pandas as pd

df = pd.read_csv('AvailableVehicles.txt', names=['RegNumber', 'Car Name', 'Price', 'Transmission Type'])
prices = df.set_index('RegNumber')['Price']

# this could be in a loop
regNumber = input("Please enter Registration Number of Car: ")

if regNumber in prices.index:
    print(f'The price is: {prices.get(regNumber)}')
else:
    print('Registration number not found')

Output:

Please enter Registration Number of Car: H4E-11
The price is: 66

CodePudding user response:

You can use the index method to find out which row matched the registration number then you would have to re-open your file and loop to that line and get the price.

It would be much easier to get the price by comparing the registration number while you are looping through the file the first time. Then if you find a match you can just print the price immediate and break out of the loop, avoiding iterating the remaining lines needlessly

For example:

def returnCar():
    regNumber = str(input("Please enter Registration Number of Car: "))
    with open("../AvailableVehicles.txt", "r", encoding="utf-8") as f:
        for data in f:
            line = data.split(',')
            if line[0] == regNumber:
                price = line[2]
                print(f'The price is: ${price} dollars')
                break
  • Related