如何从csv文件中的行打印特定字段以及如何将输入写入csv文件?

时间:2014-03-27 09:37:07

标签: python python-2.7 csv

我正在尝试创建一个拼写测试函数,其中10个单词的定义已作为一个记录(例如,definition_1,definition_2等)存在于csv(txt)文件中。我试图分别打印每一个并检索输入作为变量,之后可以存储在另一个csv文件中。这是我已经得到的,但我似乎没有运气代码运气。请注意我刚开始学习编码。

def sit_a_test():
    print "Test"
    ## Reads and prints each row of the csv file to display the definition of the allocated word.
    cr = csv.reader(open('Test.txt','rb'))
    for row in reader:
        print "Defintion 1: ",row[0]
            # Allows the user to input their answer in response to the definition. Saves the input as a variable. Repeats for each row.
        answer = raw_input("Answer: ")

        print "Defintion 2: ",row[1]

        answer_2 = raw_input("Answer: ")

        print "Defintion 3: ",row[2]

        answer_3 = raw_input("Answer: ")

        print "Defintion 4: ",row[3]

        answer_4 = raw_input("Answer: ")

        print "Defintion 5: ",row[4]

        answer_5 = raw_input("Answer: ")

        print "Defintion 6: ",row[5]

        answer_6 = raw_input("Answer: ")

        print "Defintion 7: ",row[6]

        answer_7 = raw_input("Answer: ")

        print "Defintion 8: ",row[7]

        answer_8 = raw_input("Answer: ")

        print "Defintion 9: ",row[8]

        answer_9 = raw_input("Answer: ")

        print "Defintion 10: ",row[9]

        answer_10 = raw_input("Answer: ")

    ## Writes answer inputs to the csv file in preperation to be calculated as a score.
    with open('Score.txt','w',newline='') as fp:
        a = csv.writer(fp,delimeter=',')
        data = [answer,answer_2,asnwer_3,answer_4,answer_5,answer_6,answer_7,answer_8,answer_9,answer_10]

1 个答案:

答案 0 :(得分:0)

我会稍微分解一下:

def ask_question(number, definition):
   """ Asks a question for definition number """
   print "Definition {}: {}".format(number, definition)
   return raw_input("Answer: ")

def sit_a_test():
   results = []
   with open("Test.txt", "rb") as f:
       for row in csv.reader(f):
           results.append(list(ask_question(no, def) for no, def in enumerate(row))))

   with open("Score.txt", "wb") as f:
       writer = csv.writer(f)
       writerow.writerows(results)

ask_question()函数询问带有定义编号和定义的问题,并返回用户的答案。答案收集在一个列表中。每个列表都包含来自Test.txt定义的单行答案。我假设你的csv文件包含这样的行

definition_1, definition_2, definition_3..
definition_1, definition_2, definition_3..
definition_1, definition_2, definition_3..