Is there a way to read specific values of a row in python 3 for csv file?

Viewed 34

I would like to do read only the value of the last column Existing Policies through the input of Customer NRIC number. For example, when I input S876XXXXF, the output should give me existing policies: Investments and Travel.

Here is the csv file data:

Customer NRIC,Customer Name,Date of Birth,Existing Policies
S876XXXXF,John Tan,7-Oct-87,Investments and Travel
T019XXXXA,Alice Lim,14-Apr-01,Savings 
S921XXXXK,Sam Chua,19-Aug-92,Savings and Investment

Here is what I have coded so far and got stuck:

import csv

filename = "database.csv"
nric = input("Enter your NRIC number: ")

file = open(filename,"r")

with open("database.csv") as customer_info:
    csv_pointer = csv.reader(customer_info)
    for each in csv_pointer:
        print(each[-1])

Thank you!

1 Answers
with open('database.csv') as csvfile:
    csv_pointer = csv.reader(csvfile, delimiter=',')
    for row in csv_pointer:
        print(row)

Firstly, do this, and you'll begin to understand what the individual variables are storing. Then I believe you should be able to do the rest of the code to only output the specific NRIC number. Below is the solution if you're still unable to get it.

nric = input("Enter your NRIC number: ")
with open('database.csv', newline='') as csvfile:
    csv_pointer = csv.reader(csvfile, delimiter=',')
    for row in csv_pointer:
        if row[0]==nric:
            print(row[-1])
Related