如何检查输入是否位于 .txt 文件的特定行?
How can I check if an input is on a certain line of a .txt file?
我正在 python 创建一个简单的测验程序,使用文本文件来存储问题和答案。有没有办法检查输入是否在文本文件的第 3 行(例如)。
我尝试过其他有效的方法,但它们会检查整个文件或前三行,而不仅仅是第 3 行。(注意:我也收到索引错误 - 使用下面的代码,字符串索引超出范围)
有什么帮助吗?
答案文本文件:
问题的文本文件:
错误:
def questions():
question_answered = 0 # sets number of questions answered to zero
lineq = 6 # sets the number of lines to output from questions.txt
linea = 0 # sets the number of linea to read from answers.txt
score = 0 # sets initial score to 0
with open("questions.txt", "r") as q:
with open("answers.txt", "r") as a:
while question_answered != 3:
linea += 1
question_answered += 1
for i in range(lineq):
line = (q.readline())
print(line)
response = input("answer:")
check_line = a.readline()
if response in check_line[linea]:
score += 1
print("correct")
print(check_line[linea])
print("score:", score)
questions()
您应该考虑使用此代码段:(其中 f 是文件对象)
lines = f.readlines()
现在 lines
是一个 list
对象,每行都有字符串。
请注意,它们以 "\n"
结尾
也许在程序开头读取文件然后使用本地程序内存会更容易。
我正在 python 创建一个简单的测验程序,使用文本文件来存储问题和答案。有没有办法检查输入是否在文本文件的第 3 行(例如)。
我尝试过其他有效的方法,但它们会检查整个文件或前三行,而不仅仅是第 3 行。(注意:我也收到索引错误 - 使用下面的代码,字符串索引超出范围)
有什么帮助吗?
答案文本文件:
问题的文本文件:
错误:
def questions():
question_answered = 0 # sets number of questions answered to zero
lineq = 6 # sets the number of lines to output from questions.txt
linea = 0 # sets the number of linea to read from answers.txt
score = 0 # sets initial score to 0
with open("questions.txt", "r") as q:
with open("answers.txt", "r") as a:
while question_answered != 3:
linea += 1
question_answered += 1
for i in range(lineq):
line = (q.readline())
print(line)
response = input("answer:")
check_line = a.readline()
if response in check_line[linea]:
score += 1
print("correct")
print(check_line[linea])
print("score:", score)
questions()
您应该考虑使用此代码段:(其中 f 是文件对象)
lines = f.readlines()
现在 lines
是一个 list
对象,每行都有字符串。
请注意,它们以 "\n"
也许在程序开头读取文件然后使用本地程序内存会更容易。