D Clark
D Clark

Reputation: 1

Attempting to Write to a text file using f.write in Python

I am attempting to write information to a text file. I have a class "Student" that has a "title" and "grade" I am new to python and am unsure of proper syntax for f.write. I have already used input to get a student name, which is in "stud" which is of type "Student"

I have been attempting to amend the syntax, but to no avail

from studentStruct import Student
from assignments import Assignments

def SaveStudentToStudentList(stud):
    f = open("studentlist.txt", "a")
    f.write(str(stud.name) + (" ") + str(stud.grade) + ("\n"))
    f.close()

def CalculateStudentGrade(assignmentList, assignNum):
    sum = 0
    i = 0
    total = 0
    while i < assignNum:
        print("Enter the grade for " + assignmentList[i].title)
        mark = input("")
        sum += float(mark)*float(assignmentList[i].weight)
        total += float(assignmentList[i].weight)
        i += 1

    grade = round(sum/total)
    return grade

def DisplayStudentList(studentList, numOfStudents):
    return

numOfStudents = 0
studentList = []
assignmentList = []
assignNum = 0
canUseThree = False
canUseOne = True

print("|*|*|GRADEBOOK v1.0|*|*|\n(1): Enter First student and assessments\n(2): Display Student List\n (3): Enter New student\n (4): Exit\n")

while 1:
    choice = input("")

    if choice == "1":
        if not canUseOne:
            continue

        while 1:
            print("Enter an assignment name. Type STOP if done: \n")
            assign = input("")
            if assign == "STOP":
                break
            print("Enter the weight: \n")
            weight = input("")
            assignmentList.append(Assignments(assign, weight))
            assignNum += 1

        print("Enter the student name: ")
        StudentName = input("")
        grade = CalculateStudentGrade(assignmentList, assignNum)
        print(("Student has achieved ") +str(grade))
        if grade < 50:
            print("This student has failed the course.")
        if grade > 100:
            print("Student has over-achieved. A mark of 100 will be submitted.")
            grade = 100;
        studentList.append(Student(StudentName, grade))
        canUseOne = False
        SaveStudentToStudentList(studentList[numOfStudents])
        numOfStudents += 1

Upvotes: 0

Views: 983

Answers (2)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

You can create the text string first and then write it

text = '{} {}\n'.format(str(stud.name), str(stud.grade))
f.write(text)

For e.g.

text = '{} {}\n'.format(str('John'), str('A'))
#John A
f.write(text)

Upvotes: 0

rdas
rdas

Reputation: 21275

f.write can take a string as an argument. So just pass a proper string.

f.write(str(stud.name)  + " " + str(stud.grade) + "\n")

Upvotes: 1

Related Questions