从文件读取并写入另一个文件

时间:2020-10-08 14:42:40

标签: python file input

我对我正在从事的项目有疑问。我试图在互联网上搜索问题的答案,但找不到任何答案。所以我在这里 我有一个包含问题的txt文件(彼此之间),我想向用户一一提问。提出问题时,我希望用户输入(“ Y”或“ N”)。如果答案是“ Y”或“ N”,我想在另一个空的txt文件中写出所问的问题和给出的输入。如果答案不是“ Y”或“ N”,则我要打印给定的输入无效,并且在打印语句后,我想再次询问相同的问题。

输入后,我想再次重复此过程,但要回答下一个问题,直到用完txt文件中的所有问题为止。

我知道不多,但这是我的代码:

def import_vragenlijst():

    with open ("vragen.txt", "r") as rf:
        lezen = rf.readline()
        print(lezen)
        # with open ("antwoorden_gebruiker.txt", "w") as wf:
        


def main():
    # naam()
    import_vragenlijst()
    
if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:0)

您希望将任务分解为较小的部分,以便可以单独处理。

  • 从一个文件中读取问题列表
  • 将问题/答案行写到另一个文件
  • 向用户提出问题
  • 收集用户的答案
  • 确定响应是否有效

除非您期望有一个庞大的问题列表,否则请考虑将整个列表读入一个数组。同样,除非试图将答案写到文件中,否则应考虑将答案写到数组中,除非出于某种原因在用户回答时需要将答案写出。

所以您会遇到这样的情况(未经测试,不要以为只要您不花力气就可以工作):

def query_user(question):
   response = input(question)
   if is_valid(response):
      return response
   else:
      print(f'{response} is not valid, must by "Y" or "N"')
      # recur, asking the user again
      return query_user(question)
   
def is_valid(response):
  return response == "Y" or response == "N"

def main():
   # open up the file, then read all the questions into memory
   with open(question_filename, "r") as questions_file:
       questions = [question for question in questions_file.read()]
   
   # create an array of answers based on user input
   answers = [query_user(question) for question in questions]

   # open the answers file and write the questions and answers out
   with open(answered_questions_filename, "w") as answers_file:
       for question, answer in zip(questions, answers):
           answers_file.writeline(question)
           answers_file.writeline(answer)