尝试在Python中使用f.write写入文本文件

时间:2019-04-17 04:43:50

标签: python python-3.x

我正在尝试将信息写入文本文件。我有一个“学生”类,其中有一个“标题”和“成绩” 我是python新手,不确定f.write的语法是否正确。 我已经使用输入来获取学生姓名,该姓名位于“学生”类型的“ stud”中

我一直在尝试修改语法,但无济于事

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

2 个答案:

答案 0 :(得分:1)

f.write可以将字符串作为参数。因此,只需传递适当的字符串即可。

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

答案 1 :(得分:0)

您可以先创建文本字符串,然后再编写

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

例如

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