我尝试打开两个文本文件,读取它们的内容,并将其放入两个单独的临时文件中以便稍后调用。 我遇到了以下两个问题:
我的内容文件
- 为什么test_questions列表中前两个字符串后面有这么多''?
- 为什么应该填充test_answers列表的字符串被添加到test_questions列表中?
代码如下:
from os import read
# vars to hold questions and answers from question bank and answer bank in format ready for quiz iterations
test_questions = []
test_answers = []
# placing questions in temp list called test_questions
def read_quest():
bank = open("test_question_bank.txt", "r+")
bank.seek(0)
file_read_q = bank.readlines()
start = 0
stop = 5
for i in file_read_q:
temp_q = "".join(file_read_q[start:stop])
print(test_questions.append(temp_q))
start += 5
stop += 5
bank.close()
# placing answers in temp list called test_answers
def read_answers():
ans = open("test_correct_ans.txt", "r+")
file_read_a = ans.readlines()
ans.seek(0)
for i in file_read_a:
i = i.strip("\n")
print(test_questions.append(i))
ans.close()
# adding questions
def add_quest():
bank = open("test_question_bank.txt", "a")
correct_ans = open("test_correct_ans.txt", "a")
prompt = input("Please write question: ")
ansa = input("Write answer for choice a): ")
ansb = input("Write answer for choice b): ")
ansc = input("Write answer for choice c): ")
correct_opt = input("Which option is the correct answer? ")
temp_quest = prompt + "\n(a) " + ansa + "\n(b) " + ansb + "\n(c) " + ansc + "\n\n"
temp_quest2 = "".join(temp_quest)
print(bank.write(temp_quest2))
print(correct_ans.write(correct_opt + "\n"))
bank.close()
correct_ans.close()
read_quest()
read_answers()
print(test_questions)
print(test_answers)
#add_quest()
输出结果如下:
None
None
None
None
None
None
None
None
None
None
None
None
['Where is North?\n(a) s\n(b) e\n(c) n\n\n', 'Where is South?\n(a) s\n(b) e\n(c) n\n\n', '', '', '', '', '', '', '', '', 'c', 'a']
[]
test_question_bank.txt
的内容如下:
Where is North?
(a) s
(b) e
(c) n
Where is South?
(a) s
(b) e
(c) n
我的内容文件
test_correct_answers.txt
看起来是这个样子的:c
a
return
的概念?你正在打印list.append()
和file.write()
的return
值,它们都是None
。这对我来说似乎是不必要的。你可以直接调用函数而不会在控制台上输出None
。 - Einliterflascheread_answers
中,将文件read_answers.txt
的内容附加到列表test_questions
中(如行print(test_questions.append(i))
所示)是有意为之吗?我原本以为你想将文件read_answers.txt
的内容附加到此函数中的列表test_answers
中。另外,打印append
的结果没有任何意义,应该先附加再打印列表的新元素。 - Kapoios