csv 当使用for函数进行迭代时,如何停止追加到一个列表并启动另一个列表?

wj8zmpe1  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(84)

我正在尝试添加更多的用户,将回答一些问题。但新文件保存他们的答案,显示在一行的答案。因此,用户和他们的答案与他们各自的标题不匹配。在这个例子中,我输入了3个用户,他们回答了3个问题;并在使用Pandas创建表时收到这些错误消息。
pandas.errors.ParserError:标记数据时出错。C错误:第5行中需要3个字段,锯9
我尝试使用元组,但没有任何效果。谢谢.

def example():
"""Get answers from the new users and save them in file answers.csv"""
#`Open file named filename_answers in append mode a+
   filename_answers = answers.csv
   fanswers_new_users = open(filename_answers, "a+")
   writer_answers_new = csv.writer(fanswers_new_users)
   questions_add_user = str(input("Do you wish to add another user?Enter Yes/No to continue"))
   q_ = questions_add_user.title()
   print("These are new user answers:\n")
   while q_ == "Yes":
    #headers_questions_enumerate is a list holding all enumerated questions
      for preguntas in headers_questions_enumerate[:]:
         print(preguntas)
         preguntar_1 = str(input("Please, Answer the question:\n"))
         preguntar_ = preguntar_1.title()
         respuestas_new_user.append(preguntar_)
      questions_add_user = str(input("Do you wish to add user?Enter Yes/No to continue \n"))      
      q_ = questions_add_user.title()   
      if q_! = "Yes":
      for rep in respuestas_new_user:
         respuestas_new_user_save.append(rep)
      values_dictionary.append(respuestas_new_user_save)
      for separados in values_dictionary:
         pegar_defintivo.append(separados)
      writer_answers_new.writerows(pegar_defintivo)
      fanswers_new_users.close()
      break
aydmsdu9

aydmsdu91#

您应该为每个用户重置respuestas_new_user_save列表。

import csv

def example():
    """Get answers from the new users and save them in the file answers.csv"""
    filename_answers = 'answers.csv'  # Make sure to enclose the filename in quotes
    fanswers_new_users = open(filename_answers, "a+")
    writer_answers_new = csv.writer(fanswers_new_users)
    questions_add_user = str(input("Do you wish to add another user? Enter Yes/No to continue"))
    q_ = questions_add_user.title()
    print("These are new user answers:\n")
    
    while q_ == "Yes":
        respuestas_new_user_save = []  # Reset the list for each user
        for preguntas in headers_questions_enumerate[:]:
            print(preguntas)
            preguntar_1 = str(input("Please, Answer the question:\n"))
            preguntar_ = preguntar_1.title()
            respuestas_new_user_save.append(preguntar_)
        
        questions_add_user = str(input("Do you wish to add user? Enter Yes/No to continue\n"))
        q_ = questions_add_user.title()
        
        if q_ != "Yes":
            writer_answers_new.writerow(respuestas_new_user_save)  # Write the user's answers to a new row
            fanswers_new_users.close()
            break

example()

相关问题