[英]How do I print specific fields from rows in a csv file and how to write input to a csv file?
I am trying to create a spelling test function where the definitions of 10 words are already in a csv (txt) file as one record (eg. definition_1,definition_2,etc.). 我正在尝试创建一个拼写测试功能,其中10个单词的定义已作为一个记录(例如definition_1,definition_2等)存储在csv(txt)文件中。 I am trying to print each one separately and retrieve an input as a variable, which could be stored in another csv file afterwards. 我试图分别打印每个,并检索输入作为变量,然后可以将其存储在另一个csv文件中。 This is as far as I have gotten, but I don't seem to be having any luck with the code working. 就我所知,这似乎对代码的运行没有任何帮助。 Please take into consideration that I have just started learning to code. 请考虑到我刚刚开始学习编码。
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]
I would break this up a little: 我会分解一下:
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)
The ask_question()
function asks a question with a definition number and the definition and returns the answer from the user. ask_question()
函数会问一个带有定义编号和定义的问题,并从用户那里返回答案。 The answers are gathered in a list. 答案收集在列表中。 Each list contains the answers from a single row for the definition from the Test.txt
. 每个列表都包含一行来自Test.txt
的答案。 I assume that your csv-file contains rows like this 我假设您的csv文件包含这样的行
definition_1, definition_2, definition_3..
definition_1, definition_2, definition_3..
definition_1, definition_2, definition_3..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.