How do I display data from CSV based on user input?

csv tutorial
how to import csv file in python
how to read csv file
python read csv line by line
csv file reader
creating a csv file based on user input in python
python read csv into variables
display csv file in tkinter

I'm new to Python, and my tutor taught us about formatting, if else statements and print. He wants us to use the import function to read data from a CSV file, and he gave us a starting piece of code to help us with that, which is:

import csv
filePath = "data.csv"
with open(filePath) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row['first_name'], row['last_name'])

The CSV file contains the following:

first_name,last_name,student_id,CSIT110,CSIT121,CSIT135,CSIT142
Peter,Tan,S1012342D,89,67,54,78
John,Lim,S1014322H,87,78,86,67
Ada,Ang,S1023456I,54,78,65,54

So what the objective is, is to prompt the user for their student number. And if the student number exists, it prints out their name, ID and grades. So far, my code is this:

import csv
filePath = "data.csv"
student_num=input("Enter student ID:")
with open(filePath) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
    #average =    int((row['CSIT110'])+int(row['CSIT121'])+int(row['CSIT135'])+int(row['CSIT142']))/4
        if (student_num == ""):
            print("Empty input. Please enter again.")       
        elif (student_num == "S1012342D"):
            print("=================")
            print("Student's details")
            print("=================")
            print("Student ID | First Name | Last Name")
            print("{0:<10} |{1:>11} | {2:<10}".format(row['student_id'],row['first_name'],row['last_name']))
            print("===============================================")
            print("CSIT110 | CSIT121 | CSIT135 | CSIT142 | Average")
            print("{0:^8}|{1:^9}|{2:^9}|{3:^9}|".format(row['CSIT110'],row['CSIT121'],row['CSIT135'],row['CSIT142']))

        elif (student_num == "S1014322H"):
            print("=================")
            print("Student ID | First Name | Last Name")
            print("{0:<10} |{1:>11} | {2:<10}".format(row['student_id'],row['first_name'],row['last_name']))
        else:
            print("No student record found.")

When I type one of the student ID, it just loops and prints out all the details. Would love some help!


You need to compare the entered student ID with the ones in the file line-by-line.

import csv
filePath = "data.csv"
student_num=input("Enter student ID:")
if (student_num == ""):
    print("Empty input. Please enter again.")
found = False
with open(filePath) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        if (row['student_id'] == student_num):
            average =    int((row['CSIT110'])+int(row['CSIT121'])+int(row['CSIT135'])+int(row['CSIT142']))/4
            print("=================")
            print("Student's details")
            print("=================")
            print("Student ID | First Name | Last Name")
            print("{0:<10} |{1:>11} | {2:<10}".format(row['student_id'],row['first_name'],row['last_name']))
            print("===============================================")
            print("CSIT110 | CSIT121 | CSIT135 | CSIT142 | Average")
            print("{0:^8}|{1:^9}|{2:^9}|{3:^9}|".format(row['CSIT110'],row['CSIT121'],row['CSIT135'],row['CSIT142']))
            found = True
            break
if not found:
    print("No student record found.")

argv (for the only argument) or built-in argparse library (for more flexible argument parsing). When you get user input, use it to display data with pandas means (i.e.  So if the student ID that the user input matches what's in the CSV, then it will display the data of that student. – AzaqiOct 5 '18 at 15:47. Whats in the CSV and what you write as a hardcoded check are not the same thing, though– roganjoshOct 5 '18 at 15:57. add a comment |.


I will create an example to create a list based on user input. The following is an The following is the data that we have successfully generated in CSV: data.csv Get user input to choose proper CSV file or proper row(s), field(s) of known CSV file from user input Obtain data from CSV file If your interface is command line, you can use either input() function for interactive input during script run or arguments parsing.


If I understand you would catch information about a student by them ID. Try it :

import csv
filePath = "data.csv"
student_num=input("Enter student ID:")
with open(filePath) as csvfile:
    reader = csv.DictReader(csvfile)
    not_found = True
    for row in reader:
        if student_num == row['student_id']:
            not_found = False
            print("=================")
            print("Student's details")
            print("=================")
            print("Student ID | First Name | Last Name")
            print("{0:<10} |{1:>11} | {2:    <10}".format(row['student_id'],row['first_name'],row['last_name']))
            print("===============================================")
            print("CSIT110 | CSIT121 | CSIT135 | CSIT142 | Average")
            print("{0:^8}|{1:^9}|{2:^9}|{3:^9}|".format(row['CSIT110'],row['CSIT121'],row['CSIT135'],row['CSIT142']))
    if not_found:
        print("No student record found.")

CSV File management in C++ is similar to text-type file management, except for a few modifications. compare row[0] with the roll number input by the user, and if it matches, display the details of the student Read data from a file and compare it with the user input, as explained under read operation. Based on 2 vote(s). However, many times it is required to display the CSV files in web pages as HTML tables. As most times the data is generated on the fly it requires some JavaScript to turn the CSV data to HTML. One of my current favorite is the csv-to-html-table library. This allows you to easily integrate CSV files into your web pages.


Create a simple graphical user interface (GUI) with an input box. Once you click on that button, the CSV file will be imported into Python based on the variable  How to load desktop CSV file into R/Sshiny app. GitHub Gist: instantly share code, notes, and snippets.


retrieve via fetch API, a .csv file and parse it into a JS matrix (array of array). It displays the matrix into a table that can filter and order rows based on user input. or. The filename field (data from previous steps) Specify the name of the CSV file to read from. or. Select the fieldname that will contain the filename (s) to read from. If this step receives data from a previous step, this option is enabled as well as the option to include the filename in the output. Delimiter.


Your deletion logic needs changing. Try this: Hide Copy Code. for row in reader: if deletion != row['id']: writer.writerow(row) ; # write all  How can i export the values of the text box in html to a csv or a excel .I have created an HTML Form which will be used from a local computer and want the form data to be saved in CSV file. Each time the form is submitted, it should add a line in the CSV file. This needs to be run locally so cannot use PHP or JSP.