'How can I number the lines of a .txt file and edit certain information from a selected line? (Python)

I have a .txt file with the names and information as below

John, 87, 64, 72, 79, 81, Yes

Steve, 32, 45, 29, 37, 34, No

I am trying to read from the .txt file and number each name so that the specific name can be selected by entering the number and information from the selected name can be edited.

I want to be able to choose from two options "to edit one of the amounts" or "change from No to Yes"

line_count = 0

with open("results.txt", 'r') as r_file:
            for line in r_file:
                results_info = line.split(",")
                line_count += 1
                print("\n" + str(line_count) + " " + " Name:\t" + results_info[0]
                        + "\n   " + "Subject_1:\t " + results_info[1]
                        + "\n   " + "Subject_2:\t" + results_info[2]
                        + "\n   " + "Subject_3:\t" + results_info[3]
                        + "\n   " + "Subject_4:\t" + results_info[4]
                        + "\n   " + "Subject_5:\t" + results_info[5]
                        + "\n   " + "Pass?\t" + results_info[6])
                  
student_select = input("\nEnter the number of the student to edit: ")

I've gotten this far but I am stuck when it comes to the rest.

edit:

  1. Never added subject 5 to the code

  2. I would like to write the changes made back to the .txt file

  3. Sorry, I don't think that I was clear enough. I'd like to display the list of all the students numbered. From there give the option to select a student by entering their number and then the option to edit a grade or change pass to yes.



Solution 1:[1]

So you have 3 tasks here: read data, manage user input, save data if something has been modified.

And the best structure to handle this is a dict of lists (I kept to your idea of numbering the rows, but you could easily have the student's name as key instead). The code could be something like this (some more checks are needed on user input, of course):

def edit_info(fname):
    #read data
    with open(fname, 'r') as r_file:
        info = {}
        for i,line in enumerate(r_file):
            info[str(i)] = line.rstrip().split(', ')
    #prompt user and update data
    dirty = False
    while True:
        for k,vl in info.items():
        print(f'{k:2} {vl[0]:10} {" ".join(vl[1:-1])} {vl[-1]:3}')
        student = input('Enter Student number or X to exit... ')
        if student == 'X':
            break
            if student in info:
                while True:
                    subject = input('Enter Subject number, P to set pass to yes, or X to stop editing... ')
                    if subject == 'X':
                        break
                    if subject == 'P':
                        info[student][-1] = 'Yes'
                        dirty = True
                    elif '1' <= subject <= str(len(info[student])-1):
                        subject = int(subject)
                        newvalue = input(
                            f'Enter new value for Student {student} for Subject {subject} (currently {info[student][subject]})... ')
                        info[student][subject] = newvalue
                        dirty = True
    #save data if needed
    if dirty:
        with open(fname, 'w') as w_file:
            for vl in info.values():
                w_file.write(', '.join(vl)+'\n')
    print('Completed')

Solution 2:[2]

I'm new to Python too so I will do it in a stupid way sorry. Here is my code which changes all the info of the nth student as all the input you made

def select_student_to_edit(input_num):
    all_result=[]
    result0 = input('Edit name element: ')
    result1 = " " + input('Edit 1th element: ')
    result2 = " " + input('Edit 2th element: ')
    result3 = " " + input('Edit 3th element: ')
    result4 = " " + input('Edit 4th element: ')
    result5 = " " + input('Edit 5th element: ')
    result6 = " " + input('Edit Yes/No element: ') + "\n"
    with open('test1', 'r+') as f:
        
        if input_num>1: 
            for i in range(1,input_num):
                 all_result.append(f.readline()) #If input_num = n then read n-1 line before, add all of the to a all_result list contain all lines
       
        #Start modifying the line(student) that you want to:
        
        results_info = f.readline().split(",") #Split all info into list to modify
        results_info[0] = result0
        results_info[1] = result1
        results_info[2] = result2
        results_info[3] = result3
        results_info[4] = result4
        results_info[5] = result5
        results_info[6] = result6
        
        all_result.append(",".join(results_info)) #add modified studen to all_result list

        #Add all rest lines into all_result list
        rest_line = f.readlines()
        for line in rest_line:
            all_result.append(line)
        print(all_result)
    
    #Write all line(student) in all_result into the old file
    with open('test1','w+') as f:
        for line in all_result:
            f.write(line)


select_student_to_edit(int(input('Enter the student you want to change info (nth): ')))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gimix
Solution 2