【问题标题】:I want to remove a line in a text file by asking the user to input an attribute in the line to delete it我想通过要求用户在该行中输入一个属性来删除它来删除文本文件中的一行
【发布时间】:2022-12-12 11:03:49
【问题描述】:

所以我有一个包含 ID、学生姓名和其他属性的 txt 文件。我被要求为用户提供从文件中删除学生的选项,方法是要求他们输入他们的 ID 或仅输入他们的姓名。有任何想法吗?

   ID    Name

例如['102', '迈克尔杰克逊', '3', '54', '30', '84']

def getlist():
    fp = open("student.txt", "r")
    list = fp.readlines()
    for i in range(len(list)):
        list[i] = list[i].split(";")
    return list

print("removing Students from the class based on")
        print("1-ID\t2-Student Name")
        fp=open("student.txt","r")
        
        list = getlist()
        c=int(input("Enter your choice:"))
        if(c==1):
            a=int(input("Enter the ID to remove:"))
            for i in range(1,len(list)):
                    if a==int(list[i][0]):
                        list.remove(list[i])
        else:
            b=input("Enter the Student name to remove")
            print("Records found under the name"+"("+b+")")
            for i in range(len(list)):
                if b==list[i][1]:
                    print(list[i],end=" ")
                    print("\n")

            ####this is for students with the same name
            z=int(input("Please select which record ID to remove:"))    
            
            for i in range(1,len(list)):
                #print(i)
                if z==int(list[i][0]):
                    list.remove(list[i])
                    break

【问题讨论】:

  • 你的问题是什么?

标签: python python-3.x


【解决方案1】:

您的项目即将完成。您只需要创建一个函数来保存文件。

注释:

  • getlist 重命名为 load_records。 “得到”是为了立即的事情; “加载”是指您重新获取一些东西。将“list”重命名为“records”(或“pupils”或“db”),因为它更具描述性(在 Python 中将变量命名为“list”并不是一个好主意,因为它是内置函数的名称).

  • abz重命名为nameid

  • 也有save_records

  • 如果可以,尽量不要使用for i in range(len(list)) 样式。

例如,而不是:

list = fp.readlines()
for i in range(len(list)):
    list[i] = list[i].split(";")
return list

做:

list = []
for line in fp:
    list.append(line.split(';'))
return list

(更有经验的程序员会把这个函数写成:

def load_records():
    with open("student.txt") as f:
        return [ line.split(';') for line in f ]

)

  • 同样,而不是:

          for i in range(len(list)):
              if b==list[i][1]:
                  print(list[i],end=" ")
                  print("
    ")
    

做:

        for rec in records:
            if b == rec[1]:
                print(rec, end=" ")
                print("
")

(有经验的程序员只会写print([ rec for rec in records if rec[1] == b ])。)

  • 您复制了删除记录的代码。这不好。将删除记录(按 ID)的代码移到单独的函数中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 2013-05-13
    • 2023-03-15
    相关资源
    最近更新 更多