该功能应该(A)将文件的内容存储到列表中,(B)检查列表的内容是否与另一个列表的内容相同。但是,当我运行该程序时,根本没有任何东西出现。好像这个函数不在我的代码中.....
while True:
try:
fileObject = open("studentAnswers.txt", "r")
index = 0
correctAnswers = ["B", "D", "A", "A", "C", "A", "B", "A", "C", "D", \
"B", "C", "D", "A", "D", "C", "C", "B", "D", "A"]
studentAnswers = []
fileObject.readlines()
for line in fileObject:
studentAnswers.insert(index, line)
index += 1
index = 0
for element in studentAnswers:
if element == correctAnswers[index]:
print("Question #", index, "is correct!")
else:
print("Question #", index, "is incorrect.")
index += 1
fileObject.close()
except ValueError:
print("Error.")
break
else:
break
答案 0 :(得分:5)
删除该行:
fileObject.readlines()
因为发生的事情是文件的指针到达文件的末尾,当你试图在下一个for循环中迭代它时,它实际上里面没有任何数据。
考虑以下示例:
>>> import StringIO
>>> output = StringIO.StringIO('aaaa\nbbb\nccc')
>>> output.readlines()
['aaaa\n', 'bbb\n', 'ccc']
>>> output.tell()
12
>>> for line in output:
... print line
...
>>>
>>> output.seek(0)
>>> for line in output:
... print line
...
aaaa
bbb
ccc
>>>