阅读和使用CSV文件

时间:2015-03-01 06:45:21

标签: python csv

我有以下测验计划

def trivia():
score=0
myFile = open("farming.csv","r") # opens the CSV file and stores it in the array myFile
lines = myFile.readlines() # reads the lines of the CSV file into the variable players
questionnum=1
while questionnum < 6:

    for p in lines:
        data = p.split(",") #splits each cell of the CSV file into its parts
    questions = data[0]
    answera = data[1]
    answerb = data[2]
    answerc = data[3]
    CorrectAnswer = data[4]
    print("Question #",questionnum)
    print(questions) #prints the question and the 3 answers
    time.sleep(0.5)
    print(answera)
    time.sleep(0.5)
    print(answerb)
    time.sleep(0.5)
    print(answerc)
    time.sleep(0.5)
    answer = input("Answer? ") #asks the user for their answer
    time.sleep(1)
    print(".")
    time.sleep(1)
    print(".")
    time.sleep(1)
    print(".")

    if answer == CorrectAnswer: #checks if the answer is correct and prints approptiate responses
        print("That is the correct answer")
        score=score+1
        time.sleep(1)
    else:
        print("That is not the correct answer")
        time.sleep(1)
    print("Your current score is", score)
    print("")

    questionnum = questionnum+1

myFile.close()

问题是,当它循环时,它只会使用csv文件中的第一个问题,而不会进展到下一个问题。我该怎么做呢? 和 如果我想将问题随机化,我该怎么做?我尝试过玩random.choice,但似乎无法让它发挥作用。

提前致谢.... CS

1 个答案:

答案 0 :(得分:0)

问题是拆分“,”

的界限
for p in lines:
    data = p.split(",") #splits each cell of the CSV file into its parts

执行此操作时,它将继续使用每一行替换data变量。因此,当for循环结束时,数据将始终仅包含文件中的最后一个问题作为单个列表。尝试这样的事情:

data = [p.strip().split(",") for p in lines]

你会想要之前进入你的while循环,所以你不要一遍又一遍地运行它。

然后data将是逗号分隔的行数组(每个都是一个列表),你可以这样索引:

questions = data[questionnum-1][0]
answera = data[questionnum-1][1]
answerb = data[questionnum-1][2]
answerc = data[questionnum-1][3]

要进行随机化工作,最简单的方法可能只是在进入你的while循环之前改变你的行,例如。

import random
random.shuffle(lines)

同样FWIW,有一个python csv库可以为你处理分隔符分割,并且更加健壮。