如何在使用文本文件输入的字典中追加内容?

2024-04-19 07:24:36 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码:

fh = open('students.txt', 'r')


def dictio_maker(direc):
    count = 0
    for line in fh:
        line = line.split(" ") #Separates each string in each line
        student_num = line[0] #Sets the first element of the list "line" as the student_num
        student_name = line[1] #Sets the second element of the list "line" as the student_name
        student_grade = line[2] #Sets the third element of the list "line" as the student_grade

        count =+ 1 #To change the key names
        direc[student_num] = [student_name,student_grade]
        student_num = "student_num" + str(count) #Changes the key names for the next iteration
        student_grade = "student_grade" + str(count)
        student_name = "student_name" + str(count)
    print(direc)
    return direc

def append(direc):
    x = input('Do you want to modify an entry? (yes/no)')
    if x == "yes":
        while True:
            try:
                student_num = int(input('Enter student num: '))
            except ValueError:
                print('Please enter a valid input')
                continue
            break

        if student_num in direc.keys():
            print('Already existing. Please enter another.')

        else: 
            fh.write(str(student_num) + " ")
            while True:
                try:
                    student_name = input('Enter student name: ' )
                except ValueError:
                    print('Please enter a valid input')
                    continue
                break
            fh.write(str(student_name) + " ")
            while True:
                try:
                    student_grade= float(int(input('Enter student grade: ')))
                except ValueError:
                    print('Please enter a valid input')
                    continue
                break

            fh.write(str(student_grade) + " " + '\n')
            dictio_maker(direc)
            print(direc)    

    else: 
        fh.close()

def main():
    direc= {}
    dictio_maker(direc)
    append(direc)

if __name__ == '__main__':
    main()

它的功能: 最初,我有一个文本文件,其中包含此程序所需的输入,格式如下:

student_num1 student_name1 student_grade1
student_num2 student_name2 student_grade2
student_num3 student_name3 student_grade3

第一个函数基本上是将输入txt文件中的文本行转换为字典“direc”中的输入

我想做的是: 现在,我要为下一个函数做的是询问用户是否要添加另一个条目。如果是,我要求用户输入学号,如果学号不存在,则接受name和grade的新值并将其添加到文本文件(students.txt)中。但是如果学生号存在,请再次要求用户输入另一个条目(学生号)

问题是: 我得到一个错误:

  File "C:/Users/Dust/Desktop/alemios_students_add.py", line 35, in append
    fh.write(str(student_num) + " ")

UnsupportedOperation: not writable

我也不确定我所做的代码是否能正常工作


Tags: thenameininputcountlinestudentnum