在Python 3.4

时间:2017-08-20 12:42:16

标签: python csv

我有一个简单的问题,但我无法找到合适的解决方案。

我有一个包含学生的csv文件'他们注册的名称和科目: 名,subject1,subject2,subject3 Student1,MN1,MN2,MN3 STUDENT2,BN1,BN2,BN3 学生三,MN4,MN5,MN6

学生需要输入他的姓名和科目名称,以检查他是否已注册该科目

我的代码:

import csv

Name = input("Please provide your name: ")
Subject = input("Please provide your Subject: ")

with open('students.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        if (row['name'] == Name and row['subject1'] == Subject or 
row['subject2'] == Subject or row['subject3'] == Subject):
            print ("You are registered. It won't take long to run your VM")
        else:
            print ("You are not registered")

我的问题是它给了我多个输出 输出: 请提供您的姓名:Student3 请提供您的主题:MN4 您还没有注册 您还没有注册 你已经注册了。它不会花费很长时间来运行您的VM

显然,应该只是: 你已经注册了。它不会花费很长时间来运行您的VM

你能帮我解决这个问题吗? 谢谢

3 个答案:

答案 0 :(得分:1)

请注意,Python中的for循环有一个可选的else子句,当循环结束而没有break语句时将执行该子句...

您的代码打印循环的每次迭代。你想要的只是在循环结束时打印...

with open('students.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        if (row['name'] == Name and (row['subject1'] == Subject or row['subject2'] == Subject or row['subject3'] == Subject)):
            print("You are registered. It won't take long to run your VM")
            break
    else:
        print("You are not registered")

答案 1 :(得分:0)

数据帧将是存储csv文件的良好结构。请仔细阅读here,无论如何都会进入您的代码。请参考以下代码。

请为此安装pandas和numpy

pip install pandas
pip install numpy

<强>代码:

import pandas as pd
import numpy as np

df = pd.read_csv("testing.csv")

Name = input("Please provide your name: ")
Subject = input("Please provide your Subject: ")

query = '(name == '+ '\'' + Name + '\'' + ') and (subject1 == '+ '\'' \
         + Subject + '\'' + ' or subject2 == ' + '\'' + Subject + '\'' \
         + ' or subject2 == ' + '\'' + Subject + '\')'

if df.query(query).empty:
    print ("You are registered. It won't take long to run your VM")
else:
    print ("You are not registered")

<强>参考:

  1. pandas query

答案 2 :(得分:0)

我相信字典最适合你:

import csv

data = {i[0]:i[1:] for i in csv.reader(open('filename.csv'))}

Name = input("Please provide your name: ")
Subject = input("Please provide your Subject: ")

if Subject in data[Name]:
    print("you are registered")
else:
    print("you are not registered")