如何在两个单独的记录中将多个输入写入csv文件?

时间:2014-03-27 10:31:35

标签: python python-2.7 csv

我试图提示用户输入拼写测试的定义和答案,每个拼写测试都可以保存为变量中的字符串并写入csv(txt)文件。但是,我也试图在单独的记录中保存单词的定义及其答案:

E.g。

    def_1,def_2,def_3,etc

    ans_1,ans_2,ans_3,etc

请注意我是编码新手,因此对Python有基本的了解。

def create_new_test():

    print "Create New Test"
# Prompts user to enter each definition and their answers.
definition = raw_input("Enter definition: ")
answer = raw_input("Enter word: ")
definition_2 = raw_input("Enter definition: ")
answer_2 = raw_input("Enter word: ")
definition_3 = raw_input("Enter definition: ")
answer_3 = raw_input("Enter word: ")
definition_4 = raw_input("Enter definition: ")
answer_4 = raw_input("Enter word: ")
definition_5 = raw_input("Enter definition: ")
answer_5 = raw_input("Enter word: ")
definition_6 = raw_input("Enter definition: ")
answer_6 = raw_input("Enter word: ")
definition_7 = raw_input("Enter definition: ")
answer_7 = raw_input("Enter word: ")
definition_8 = raw_input("Enter definition: ")
answer_8 = raw_input("Enter word: ")
definition_9 = raw_input("Enter definition: ")
answer_9 = raw_input("Enter word: ")
definition_10 = raw_input("Enter definition: ")
answer_10 = raw_input("Enter word: ")
## Writes input to the csv file. Defintions and answers are stored in two separate records.
with open('Test.txt','w',newline='') as fp:
    a = csv.writer(fp,delimeter=',')
    data    = [[definition,definition_2,definition_3,definition_4,definition_5,definition_6,definition_7,definition_8,definition_9,definition_10],
        [answer,answer_2,answer_3,answer_4,answer_5,answer_6,answer_7,answer_8,answer_9,answer_10]]
    a.writerows(data)

2 个答案:

答案 0 :(得分:1)

这是一个循环的渴望:

defs = []
answ = []
for _ in range(10):
    defs.append(raw_input("Enter definition: "))
    answ.append(raw_input("Enter word: "))
with open("test.txt", "w") as fp:
    fp.write(",".join(defs))
    fp.write(",".join(answ))

请注意,而不是例如definition_4,您现在将使用defs[3](列表索引从零开始)。您还可以轻松地循环定义:

for defn in defs:

答案 1 :(得分:0)

with open('test.txt', 'w') as fp:
    fp.write('definition,answer\n')
    for index in range(0,10):
        definition = raw_input("Enter definition: ")
        answer = raw_input("Enter word: ")

        fp.write(definition + ',' + answer + '\n')

这是你要找的吗?
这将生成一个“csv”文件,如下所示:

definition,answer
Has a long neck nad loves to eat trees,giraffe
Is blue and rain comes from it,sky
....

这是CSV文件中的常规问题+答案语法,但出于某种原因,您希望对其进行结构化,使它们水平对齐而不是垂直对齐(不确定原因..)

即将写出@jonrsharpe给出的答案,所以如果你真的想要一个水平对齐而不是一个表格,那就去吧。