Home > Enterprise >  Selecting specific row based on user input CSV reader
Selecting specific row based on user input CSV reader

Time:12-07

i'm new to python so sorry if this seems stupid: i'm trying to make a program where the user input can ask the program a "station" and it returns/print the right line.

So, for example, this is my code:

import csv

station = input("Station... ")

with open('data.csv', 'rt') as f:
    reader = csv.reader(f)
    for row in reader:
        if row == station:
            print(row)

My "data.csv" is like(https://i.stack.imgur.com/CdLRE.png). What i want is: station=input("1") then the program print "A600" and "aluminium"

CodePudding user response:

Each of your rows will actually return a list of strings, with each element representing each comma separated value. e.g.

['1', 'A600', 'Aluminium']

So you want something like:

import csv

station = input("Station... ")

with open('test.csv', 'rt') as f:
    reader = csv.reader(f)
    for row in reader:
            if station in row[0]:
                print(row[1], row[2])

Where you're checking the first "column" for station (row[0]) and then printing the last two columns (row[1] and row[2]) if there's a match.

  • Related