如何为 .txt 文件的行编号并编辑选定行的某些信息? (Python)

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

我有一个包含以下名称和信息的 .txt 文件

约翰,87 岁、64 岁、72 岁、79 岁、81 岁,是的

史蒂夫,32 岁,45 岁,29 岁,37 岁,34 岁,没有

我正在尝试从 .txt 文件中读取并为每个名称编号,以便可以通过输入编号来 select 编辑特定名称,并且可以编辑 select 编辑名称中的信息.

我希望能够从两个选项中选择“编辑其中一个金额”或“从否更改为是”

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: ")

我已经讲到这里了,但剩下的我就卡住了。

编辑:

  1. 从未将主题 5 添加到代码中

  2. 我想将所做的更改写回 .txt 文件

  3. 抱歉,我认为我不够清楚。我想显示所有编号学生的列表。从那里给 select 学生一个选项,输入他们的号码,然后选择编辑成绩或将通行证更改为是。

我也是 Python 的新手,所以我会以一种愚蠢的方式来做,抱歉。这是我的代码,它将第 n 个学生的所有信息更改为您所做的所有输入

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): ')))

所以你在这里有 3 个任务:读取数据、管理用户输入、在修改后保存数据。

处理此问题的最佳结构是 dictlist(我保留了您对行进行编号的想法,但您可以轻松地将学生的姓名作为键)。代码可能是这样的(当然,还需要对用户输入进行更多检查):

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')