首页 > 解决方案 > 我想从 .txt 文件中读取多行

问题描述

我想从.txt文件中读取多行。每行代表一个将由 NLTK Python 脚本回答的问题,然后答案将写入另一个 .txt 文件。我成功地使这种机制起作用,但仅适用于 Question.txt 文件(提取问题的文件)中的一行(一个问题)。

正如我看到的场景,我想从 Question.txt 文件中读取一行,然后脚本将回答并将答案写入 Answer.txt 文件中。然后将从 Question.txt 文件中读取第二行,依此类推。

myFile = open("Questions.txt", 'r')
user_response=str(myFile.splitlines())  # Convert the content of the txt file from list format to string format in order to be able to lower the characters later

#I also made this little implementation in order for the code not to run infinitely, so to count the number of lines :
numOfLines = len(user_response.splitlines())
numofLines -= 1

标签: pythonfilefwritefread

解决方案


在python中,文件是迭代器,所以为了避免内存中存储大数组,你的简单解决方案是:

with open("Questions.txt") as q_f, open("Answers.txt", 'w') as a_f:
    for question in q_f:
        answer = solve(question)
        a_f.write(answer+"\n")

在这里,您逐行迭代文件,回答问题并将其保存在另一个文件中,而无需将大列表保存在内存中


推荐阅读