有没有办法将CSV中的单个结果放入变量?

时间:2018-02-28 19:07:54

标签: python python-3.6

我正在学校制作一个程序,用户在某些主题上进行测验,并将结果保存到csv文件中。我设法打印出得分最高的一排,但这看起来并不整齐。

with open ('reportForFergusTwo.csv', 'r') as highScore:
            highScoreFinder=highScore
            valid3=False
            for row in highScoreFinder:
                if subjectInput in row:
                    if difficultyInput in row:
                        if ('10' or '9' or '8' or '7' or '6' or '5' or '4' or '3' or '2' or '1') in row:
                            valid3=True
                            print("The highest score for this quiz is:",row)

例如:它说,"这个测验的最高分是:化学,简单,10,Luc16"但我更愿意这样说"这个测验的最高分是:10"并且"这个分数是通过以下方式实现的:Luc16"而不是仅打印整行,不必要的细节,例如测验的内容。

我的CSV文件如下所示:

Subject,Difficulty,Score,Username
language,easy,10,Luc16
chemistry,easy,10,Luc16
maths,easy,9,Luc16
chemistry,easy,5,Eri15
chemistry,easy,6,Waf1
chemistry,easy,0,Eri15

我想如果我能找到一种方法来获取个人结果(得分和用户名)并将它们放入各自的变量中,那么以我想要的方式呈现它会更容易,并且能够如果我需要再次显示它们,请稍后在函数中引用它们。

我对编码很新,如果能做到这一点很好奇,那么我可以改善代码的外观。

编辑:为了解决这个问题,我使用str.split()来分解我的CSV行中的单个字段,以便可以通过变量选择和保存它们。接受的答案显示了我使用的解决方案,但这是我的最终代码,以防万一

with open ('details.csv', 'r') as stalking:
        stalkingReader=csv.reader(stalking)
        valid4=False
        for column in stalkingReader:
            if user in column[3]:
                valid4=True
                print("Here are the details for user {}... ".format(user))
                splitter=row.split(',')
                name=splitter[0]
                age=splitter[1]
                year=splitter[2]
                print("Name: {}".format(name))
                print("Age: {}".format(age))
                print("Year Group: {}".format(year))
                postReport()
    if valid4==False:
        print("Sorry Fergus, this user doesn't seem to be in our records.")

4 个答案:

答案 0 :(得分:1)

with open("reportForFergusTwo.csv", "r") as highScore:

    subject = []
    difficulty = []
    score = []
    name = []
    for line in highScore:
        subject.append(line.split(',')[0])
        difficulty.append(line.split(',')[1])
        score.append(line.split(',')[2])
        name.append(line.split(',')[3])

    ind = score.index(max(score)

    print("The highest score for this quiz is: ", max(score))
    print("This was achieved by ", name[ind])

with打开(并将关闭).csv文件。 然后,创建四个空列表。 接下来,我遍历文件中的每一行,然后使用逗号分隔每一行作为分隔符。这将生成一个包含四个元素的列表,这些元素将附加到每个列表中。

答案 1 :(得分:0)

您可以使用str.split()细分CSV行,以便您可以单独引用这些字段:

split_row = row.split(',')
score = split_row[2]
user = split_row[3]
print("The highest score for this quiz is: " + score)
print("This score was achieved by: " + user)

答案 2 :(得分:0)

您可以使用csv库

import csv                                                                      

with open("data", "r") as f:                                                                         
    reader = csv.reader(f)                                                         
    # skip header                                                                  
    reader.next()                                                                  
    # organize data in 2D array                                                    
    data = [ [ sub, dif, int(score), name ] for sub, dif, score, name in reader ]
    # sort by score                                                                
    data.sort(key=lambda x: x[2], reverse=True)                                    
    # pretty print                                                                 
    print "The highest score for this quiz is:", data[0][2]                        
    print "This score was achieved by:", data[0][3]  

答案 3 :(得分:0)

(代表OP发布解决方案)

为了解决这个问题,我使用str.split()来分解我的CSV行中的单个字段,以便可以通过变量选择和保存它们。接受的答案显示了我使用的解决方案,但这是我的最终代码,以防万一

with open ('details.csv', 'r') as stalking:
        stalkingReader=csv.reader(stalking)
        valid4=False
        for column in stalkingReader:
            if user in column[3]:
                valid4=True
                print("Here are the details for user {}... ".format(user))
                splitter=row.split(',')
                name=splitter[0]
                age=splitter[1]
                year=splitter[2]
                print("Name: {}".format(name))
                print("Age: {}".format(age))
                print("Year Group: {}".format(year))
                postReport()
    if valid4==False:
        print("Sorry Fergus, this user doesn't seem to be in our records.")