【问题标题】:Reading from a file and writing to another file从一个文件读取并写入另一个文件
【发布时间】:2021-01-23 15:31:02
【问题描述】:

我有一个关于我正在从事的项目的问题。我试图在互联网上搜索我的问题的答案,但我找不到任何答案。所以我在这里.. 我有一个 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()

【问题讨论】:

    标签: python file input


    【解决方案1】:

    你想把任务分解成更小的部分,你可以单独处理。

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

    除非您预计问题列表会很庞大,否则请考虑将整个列表读入一个数组。同样,在尝试将答案写入文件之前,请考虑将答案写入数组,除非出于某种原因需要在用户回答时将其写入。

    所以你会有这样的东西(未经测试,不要假设它会在你不付出一些努力的情况下工作):

    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)
    
    
    
    

    【讨论】:

      猜你喜欢
      • 2023-04-05
      • 1970-01-01
      • 2018-10-30
      • 2012-10-22
      • 1970-01-01
      • 2015-04-02
      • 1970-01-01
      • 1970-01-01
      • 2015-12-29
      相关资源
      最近更新 更多