Python -如何用另一个字符串替换文本文件中的某一行?



我正在用python创建一个测验程序。有三个文本文件,一个用于输出问题(工作),一个用于检查用户输入是否正确(工作),一个用于更新精通。后者不起作用。当一个问题被正确回答三次时,这个问题就掌握了。我想从文本文件更新精通,从0到1(依此类推)。

当我运行我的程序时,它将第一行替换为1,但是它下面的两个0丢失了,因此我收到了索引超出范围的错误。我愿意尝试其他方法。

这是我试图在我自己的程序中实现以下代码的代码:

with open('stats.txt', 'r') as file:
    # read a list of lines into data
    data = file.readlines()
print(data)
print("Your name: " + data[0])
x = "0"
# now change the 2nd line, note that you have to add a newline
data[1] = x + "n"
# and write everything back
with open('stats.txt', 'w') as file:
    file.writelines(data)

我的程序:

    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
    with open("questions.txt", "r") as q:
        with open("answers.txt", "r") as a:
            answer_lines = a.readlines()
            while question_answered != 3:
                question_answered += 1
                for i in range(lineq):
                    line2 = (q.readline())
                    print(line2)
                response = input("answer:")
                if response not in answer_lines[linea]:
                    print("incorrect")
                    mastery = (update_mastery[linea])
                    mastery = int(mastery)
                    if mastery < 1:
                        print("mastery", mastery)
                    else:
                        mastery -= 1
                        print("mastery", mastery)
                else:
                    print("correct")
                    with open("mastery.txt", "r") as m:
                        update_mastery = m.readlines()
                    mastery = update_mastery[linea]
                    mastery = int(mastery) + 1
                    mastery = str(mastery)
                    update_mastery[linea] = mastery + "n"
                    with open('mastery.txt', 'w') as m:
                        m.writelines(update_mastery[linea])
                linea += 1

questions()

questions.txt:

1)Define isotope
[A]Atoms of the same element with same number of protons and a different number of neutrons
[B]Atoms of the different element with same number of protons and a different number of neutrons
[C]Atoms of the same element with same number of neutrons and a different number of protons
[D]Atoms of the same element with same number of protons and a different number of electrons
2)Name the type of decay that occurs when, they have too many neutrons
[A]Gamma Radiation
[B]Alpha Decay
[C]Beta Plus Decay
[D]Beta Minus Decay
3)Define Coulomb
[A]1 coulomb is the quantity of charge carried past a given point if a steady current of 1 amp flows for 1 second
[B]1 coulomb is the quantity of charge carried past a given point if a steady voltage of 1 volts per 1 second
[C]1 coulomb is the quantity of current carried past a given point if a steady voltage of 1 volts per 1 second
[D]1 coulomb is the rate of flow of charge

answers.txt:

A
D
A

mastery.txt:

0
0
0

我相信使用存储在pickle中的字典来跟踪精通水平会更容易。它使处理程序的状态变得非常容易,并且修改的速度要快得多。对于一个快速的答案,我将像这样加载pickle:

"""
We are loading the pickled mastery values by checking if the pickle file exists.
If it doesn't we define a default mastery level
"""
try:
    with open("mastery.p", "rb") as mastery_file:
        mastery = pickle.load(mastery_file)
except FileNotFoundError:
    mastery = {
        "1: Define isotope": 0,
        "2: Name the type of decay that occurs when, they have too many neutrons": 0,
        "3: Define Coulomb": 0,
    }

然后可以使用mastery作为常规字典并相应地修改值。完成后,可以再次将mastery状态保存在pickle中:

def save():
    with open("mastery.p", "wb") as m:
        pickle.dump(mastery, m)

现在对于整个程序:

import pickle
"""
Here we defining the quesions and choices in a dictionary, but you could
load them from a normal text file, json file, or a pickle.
The questions are the keys to choices.
"""
q_and_a = {
    "1: Define isotope": [
        "[A]Atoms of the same element with same number of protons and a different number of neutrons",
        "[B]Atoms of the different element with same number of protons and a different number of neutrons",
        "[C]Atoms of the same element with same number of neutrons and a different number of protons",
        "[D]Atoms of the same element with same number of protons and a different number of electrons",
    ],
    "2: Name the type of decay that occurs when, they have too many neutrons": [
        "[A]Gamma Radiation",
        "[B]Alpha Decay",
        "[C]Beta Plus Decay",
        "[D]Beta Minus Decay",
    ],
    "3: Define Coulomb": [
        "[A]1 coulomb is the quantity of charge carried past a given point if a steady current of 1 amp flows for 1 second",
        "[B]1 coulomb is the quantity of charge carried past a given point if a steady voltage of 1 volts per 1 second",
        "[C]1 coulomb is the quantity of current carried past a given point if a steady voltage of 1 volts per 1 second",
        "[D]1 coulomb is the rate of flow of charge",
    ],
}
"""
The answers have been defined with the same scheme as the questions
Once again, you could load these from a file or add them as the last
item in the q_and_a and filter them out when giving the questions.
"""
answers = {
    "1: Define isotope": "a",
    "2: Name the type of decay that occurs when, they have too many neutrons": "b",
    "3: Define Coulomb": "a",
}
"""
We are loading the pickled mastery values by checking if the pickle file exists.
If it doesn't we define a default mastery level
"""
try:
    with open("mastery.p", "rb") as mastery_file:
        mastery = pickle.load(mastery_file)
except FileNotFoundError:
    mastery = {
        "1: Define isotope": 0,
        "2: Name the type of decay that occurs when, they have too many neutrons": 0,
        "3: Define Coulomb": 0,
    }
# Here, we are iterating over every question each session

def show_questions(q, choices):
    print(f"{q}:")  # Show the question
    print("n".join(choices))  # Show the choices
    answer = input("You answer: ")  # wait for answer
    if answer.lower() != answers[q]:  # convert to lowercase (to match answerkey)
        print(f"wrong, answer is {answers[q]}")
        mastery[q] -= 1
        print(f"Your mastery decreased to {mastery[q]}n")
        return False
    else:
        print("Correct!")
        mastery[q] += 1
        print(f"Your mastery increased to {mastery[q]}n")
        return True

def save():
    with open("mastery.p", "wb") as m:
        pickle.dump(mastery, m)

def loop_all():
    """
    Loops through all qustions once
    """
    for q, choices in q_and_a.items():
        show_questions(q, choices)
        save()

def for_mastery(max_level=3):
    """
    Loops through each question till mastery is reached
    Mastery can be adjusted by passing it as an argument
    """
    for q, m in mastery.items():
        print(m)
        choices = q_and_a[q]
        while m < max_level:
            passed = show_questions(q, choices)
            if passed:
                m += 1
            else:
                m -= 1
            save()
        print("mastered!n")

for_mastery()