我想从.txt文件中读取多行内容

时间:2019-06-26 14:32:59

标签: python file fwrite fread

我想从.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

3 个答案:

答案 0 :(得分:0)

Python 3

您必须做什么:

  1. 阅读所有行
  2. 计算所有答案
  3. 将所有答案写回到文件中

我假设您回答问题的方法称为answer_question(question)

# 1
with open("Questions.txt") as questions_file:
    questions = questions_file.read().splitlines()

# 2
answers = []
for question in questions:
    answer = answer_question(question)  # or use question.lower() if you want to 
    answers.append(answer)

# 3
with open("Answers.txt", mode="w") as answers_file:
    answers_file.write("\n".join(answers))

答案 1 :(得分:0)

在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")

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

答案 2 :(得分:-1)

您可以使用myFile.readlines()获取每一行的列表,也可以使用myFile.read()