如何根据用户输入显示CSV数据?

时间:2018-10-05 15:37:23

标签: python csv

我是Python的新手,我的老师教了我们有关格式化,语句和打印的信息。他希望我们使用导入功能从CSV文件中读取数据,并且他给了我们一段开始的代码来帮助我们解决这个问题,

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

CSV文件包含以下内容:

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

所以目标是向用户提示他们的学生编号。如果学生编号存在,它将打印出他们的姓名,ID和成绩。到目前为止,我的代码是这样的:

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

当我输入一个学生证时,它会循环并打印出所有详细信息。希望有帮助!

3 个答案:

答案 0 :(得分:1)

我建议您:

  • 使用for...else遍历学生ID
  • 如果ID与用户输入匹配,则使用for k,v in row.items()遍历该行以显示学生信息

这是代码:

import csv

filePath = "data.csv"

with open(filePath) as csvfile:
    reader = csv.DictReader(csvfile)
    student_id = input('Enter the sudent number: ')
    for row in reader:
        if student_id == row['student_id']:
            for k,v in row.items():
                print(k,':',v)
            break
    else:
        print('This number does not exist')

它打印Enter the sudent number:。 如果输入S1014322H,则输出以下内容:

first_name : John
last_name : Lim
student_id : S1014322H
CSIT110 : 87
CSIT121 : 78
CSIT135 : 86
CSIT142 : 67

答案 1 :(得分:0)

您需要逐行比较输入的学生ID和文件中的ID。

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

答案 2 :(得分:0)

如果我理解您会通过他们的ID来获取有关学生的信息。试试吧:

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