Добавление текста с добавлением словаря Python - PullRequest
0 голосов
/ 09 октября 2018

Проблема в том, что я хочу добавить студента в существующую запись, а затем сохранить его в txt.file, используя файл в python, однако он не будет добавляться в текстовый файл.Ожидаемый результат моего кода - добавить ДВА ученика в словарь, затем сохранить его в текстовый файл, а после прочтения этого текстового файла появятся добавленные ученики.

while True:
def Menu(): #Menu Function

    print("****Student Record****")
    print()
    print("[1] Add Student")
    print("[2] View Student")
    print("[3] View all Students")
    print("[4] Delete a Student")
    print("[5] Delete all Students")
    print("[6] Load file")
    print("[7] Save to file")
    print("[0] Exit")

def save(): #isang student lang na-aadd
    saveHandle = open("record.txt", "a")
    for k in record: #Checks each key in dictionary
        student = k #each student is assigned to the key
        i = 0
        if student == str(k): #checks if student is in dictionary
            saveHandle.write(str(new + ",") 
            for k in record[k]:
                if i == 0:
                    saveHandle.write(str(k))
                if i == 1:
                    saveHandle.write(str(k))
                if i == 2:
                    saveHandle.write(str(k))
                if i == 3:
                    saveHandle.write(str(k))
                i = i + 1
def load():
    record = [] #oks na

    readHandle = open("record.txt", "r")

    for line in readHandle:
        student = line[:-1]
        record.append(student)

    readHandle.close()

    print(record)




Menu()


print() #space

option = int(input("Enter option: "))

print()

    record = {"2018-00000" : ["Jake Peralta", "BA Communication Arts", "1st Year", "19"]}
#Current school record

if option == 1: #Adding a student in the record
    new = input("Enter student no.: ")
    newname = input("Enter name: ")
    newdegree = input("Enter degree: ")
    newyear = input("Enter year level: ")
    newage = input("Enter age: ")

    record[new]=(newname, newdegree, newyear, newage) #adding a new key and list to the dictionary


    print("Student record has been added")

elif option == 2: #View a student's record
    student = input("Enter the Student no. of the student you want to view: ")
    print()
    for k in record: #checks each key in dictionary
        i = 0
        if student == k: #checks if user input student no. is equal to any key in the dictionary
            print("Student no:",student)
            for k in record[k]: #checks each element in the list per key
                if i == 0: #first element
                    print("Name:",k)
                if i == 1: #second element
                    print("Degree:",k)
                if i == 2: #third element
                    print("Year Level:",k)
                if i == 3: #fourth element
                    print("Age:",k)
                i = i + 1 #updates each item in list    



elif option == 3: #View all students
    for k in record: #Checks each key in dictionary
        student = k #each student is assigned to the key
        i = 0
        if student == str(k): #checks if student is in dictionary
            print("Student no:",student)
            for k in record[k]: #for every item in list per key
                if i == 0:
                    print("Name:",k)
                if i == 1:
                    print("Degree:",k)
                if i == 2:
                    print("Year Level:",k)
                if i == 3:
                    print("Age:",k)
                i = i + 1
            print()
    else:
        print("No Students on the record")



elif option == 4: #Deleting a student
    xstudent = input("Enter the student no. of the student you want to delete: ")
    print()
    for k in record: #Checks each key in dictionary
        if xstudent == str(k):#Checks if user input is in dictionary
            deleted = record.pop(k) #deletes the key and value
            print("Student record has been deleted.")
        else:
            print("Student is not part of the record. ")
        break



elif option == 5: #Deletes Record
    record.clear()
    print("All student records are now deleted")



elif option == 0: #Exit
    print("Thank you. Have a nice day!")

elif option ==6: 
    load()

elif option == 7: #Save
    save()

1 Ответ

0 голосов
/ 09 октября 2018

Я считаю, что проблема в том, что переменная 'i' объявлена ​​со значением 0, но не обновлена ​​в ваших операторах 'for'.'i' должен ссылаться на объект, когда вы просматриваете свои записи.

...