简体   繁体   English

在字符串后写入文件

[英]Writing a file after a string

I want to read and write grades(numbers) after a certain subject tag(string). 我想在某个主题标签(字符串)之后读写成绩(数字)。 So I have everything but I can't figure out how to find the tag and write after without replacing the numbers that were after it. 因此,我拥有所有东西,但是我无法弄清楚如何找到标签并在不替换标签后面的数字的情况下编写标签。

So, for example, valid input would be: 因此,例如,有效输入为:

MAT54324524342211

And what I have tried so far: 到目前为止,我已经尝试过:

save = open("grades.txt", "w")

def add(x, y):
    z = x / y * 100
    return z

def calc_grade(perc):
    if perc < 50:
        return "1"
    if perc <  60:
        return "2"
    if perc < 75:
        return "3"
    if perc < 90:
        return "4"
    if perc >= 90:
        return "5"

def calc_command():
    num1 = input("Input your points: ")
    num2 = input("Input maximum points: ")
    num3 = add(float(num1), float(num2))
    grade = calc_grade(num3)
    print("This is your result:", str(num3) + "%")
    print("Your grade:", grade)
    save.write(grade)


while True:
    command = input("Input your command: ")
    if command == "CALC":
        calc_command()
    if command == "EXIT":
        break

Any ideas? 有任何想法吗? Hey sorry this is the old version of my code. 抱歉,这是我代码的旧版本。 The new version was that after printing my grade here was save.write(grade). 新版本是在打印我的成绩后,这里是save.write(grade)。 Program is not finished. 程序未完成。 The final idea is that i will get a bunch of subject tags in my txt file and then the user will pick for which subject is the grade. 最终的想法是,我将在txt文件中得到一堆主题标签,然后用户将选择哪个主题是成绩。

Please try not to reimplement things which already come with the standard library. 请尽量不要重新实现标准库中已经包含的内容。

Some implementation of your script using json would be this: 使用json实现脚本的一些实现如下:

import os
import json


def read_grades(filename):
    if os.path.exists(filename):
        with open(filename, 'r') as f:
            try:
                return json.loads(f.read())
            except ValueError as ex:
                print('could not read', ex)
    return {}


def write_grades(filename, grades):
    with open(filename, 'w') as f:
        try:
            f.write(
                json.dumps(grades, indent=2, sort_keys=True)
            )
        except TypeError as ex:
            print('could not write', ex)


def question(text, cast=str):
    try:
        inp = input(text)
        return cast(inp)
    except Exception as ex:
        print('input error', ex)
        return question(text, cast=cast)


def calculator(grades):
    def add(x, y):
        assert y != 0, 'please don\'t do that'
        z = x / y
        return z * 100

    def perc(res):
        for n, p in enumerate([50, 60, 75, 90], start=1):
            if res < p:
                return n
        return 5

    subject = question('enter subject: ').strip()
    points = question('your points: ', cast=float)
    max_points = question('maximum points: ', cast=float)

    result = add(points, max_points)
    grade = perc(result)

    print('> {subject} result: {result:.2f}% grade: {grade}'.format(
        subject=subject.capitalize(),
        result=result, grade=grade
    ))

    grades.setdefault(subject.lower(), list())
    grades[subject.lower()].append(grade)

    return grades


def show(grades):
    print('>> grades')
    for subject in sorted(grades.keys()):
        print('> {subject}: {grades}'.format(
            subject=subject.capitalize(),
            grades='; '.join(str(g) for g in grades[subject])
        ))


def main():
    filename = 'grades.json'
    grades = read_grades(filename)

    while True:

        grades = calculator(grades)
        show(grades)

        if not question('continue? (hit enter to quit) '):
            break

    write_grades(filename, grades)

if __name__ == '__main__':
    main()

The grades.json now contains a dictionary with subjects as keys, and a list of all grades as values: grades.json现在包含一dictionary以主题为键的dictionary ,以及所有成绩作为值的list

{
  "art": [
    3
  ],
  "math": [
    4,
    5
  ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM