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

Python - How do you replace a certain line in a text file with another string?

我正在使用 python 创建一个测验程序。一共有三个文本文件,一个用于输出问题(作品),一个用于检查用户是否输入正确(作品),一个用于更新掌握情况。后者不起作用。一道题答对三遍就掌握了。我想从文本文件更新掌握度,从零到一(依此类推)。

当我 运行 我的程序时,它用 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 中的字典来跟踪掌握程度会更容易。它使得处理程序的状态变得非常容易,并且修改起来要快得多。
为了快速回答,我会像这样加载泡菜:

"""
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 用作常规字典并相应地修改值。完成后,可以再次保存pickle中的mastery状态:

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()