0

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

  • Couldn't get your question. Can you demonstrate your need with some example ?? – 2rd_7 Jun 11 '16 at 06:11
  • Your question is rather vague. However, if you want to read data from that file don't open it in "w" mode. There's a good summary of all the standard file modes in [this answer](http://stackoverflow.com/a/1466036/4014959). – PM 2Ring Jun 11 '16 at 06:24
  • Ok so for example this would be in the text file: MAT54355 and i want to write after MAT. Thats because i want to sort my grades by subjects or is there a better way –  Jun 11 '16 at 06:34
  • 1
    You can't just insert data into a file. The simple way to do what you want is to read the whole file into a list of lines, search the list for the correct line, modify the line, then write the list back to the file. – PM 2Ring Jun 11 '16 at 06:49

1 Answers1

0

Please try not to reimplement things which already come with the standard library.

Some implementation of your script using json would be this:

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:

{
  "art": [
    3
  ],
  "math": [
    4,
    5
  ]
}
spky
  • 2,123
  • 2
  • 17
  • 21