Поиск определенного имени в файле, а затем изменение значения, связанного с ним, с помощью функции - PullRequest
0 голосов
/ 29 февраля 2020

Моя программа создает файлы, в которых перечислены ученики в классе и их оценки. Я пытаюсь создать функцию, которая позволяет пользователю редактировать оценку конкретного ученика в соответствующем файле класса. До сих пор мне удавалось создавать файлы и добавлять учащихся и их оценки следующим образом:

def createClass(chosenclass, data):
    classoptions = 'Class {}'.format(chosenclass)
    with open(f'{classoptions}.txt', '+w') as file:
        for key,value in data.items():
            studentdata = 'Name: {}, Score: {}/100\n'.format(key, value)
            file.write(studentdata)
    return file


command = input('Please enter a command: ')
while command:
    if command == '6':
        print('Have a good day!')
        exit()
    elif command == '1': # opt 1
        print('\n')
        askclass = input('Please enter your class: ')
        studentno = int(input('How many student\'s are in your class?: '))
        data = {}
        for i in range(0,studentno):
            askstudent = input('Please enter a student\'s full name: ')
            askscore = int(input('Please enter the student\'s score: '))
            data[askstudent] = askscore
            print('\n')
            print('Student Added!')
            createClass(askclass,data)
        command = input('Please enter a command: ')

Теперь я пытаюсь создать функцию, которая позволяет редактировать оценки любого учащегося.

Для этого я пытаюсь создать список, содержащий имя и оценку каждого учащегося из каждой строки, используя атрибут .split, а затем превращаю этот список в словарь. До сих пор я придумал это:

def convertList(listname):
    iteration = iter(listname) 
    resultant = dict(zip(iteration, iteration)) 
    return resultant

def editStudent(classfile, selectedstudent, newscore):
    with open(f'Class {classfile}.txt', '+w') as chosen:
        for line in chosen:
            listver = line.split(',')
        data = convertList(listver)
        for key, value in data.items():
            if key == 'Name: ' + str(selectedstudent):
                formattedresult = 'Score: {}/100'.format(newscore)
                value.replace(value, formattedresult)
                final = print('New result is ' + newscore + '/100')
                return final

if command == '3':
        whichfile = input('Which class would you like to edit?: ')
        whichstudent = input('Which student would you like to edit?: ')
        whichscore = input('Please enter the updated score: ')
        editStudent(whichfile,whichstudent,whichscore)
        command = input('Please enter a command: ')

Однако, когда я запускаю это, я получаю следующую ошибку:

Traceback (most recent call last):
  File "/Users/sinclair_ma/Desktop/IST AT1/testing.py", line 90, in <module>
    editStudent(whichfile,whichstudent,whichscore)
  File "/Users/sinclair_ma/Desktop/IST AT1/testing.py", line 48, in editStudent
    data = convertList(listver)
UnboundLocalError: local variable 'listver' referenced before assignment

У меня такое ощущение, что я иду не так Кстати, попытка заменить значения, но у меня возникли проблемы с поиском каких-либо альтернатив. Буду признателен за любую помощь, чтобы направить меня в правильном направлении.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...