使用csv阅读器从文件中删除行并列出python

使用csv阅读器从文件中删除行并列出python,python,csv,Python,Csv,在这方面也有类似的问题,但没有一个涉及到我需要的细节 我有以下代码,根据指定的用户输入,试图删除文件中的一行。方法是 将文件读入列表 删除列表中的相关行(最好是在列表中阅读时?) 重写文件 我想对第2和第3部分提供一些指导和意见,以及如何使用csv reader在python中执行这种简单的删除/编辑操作的最佳解决方案(对于初学者,出于教学/学习目的) 代码 """ ==============TASK 1. Search for any given username 2. Delete the

在这方面也有类似的问题,但没有一个涉及到我需要的细节

我有以下代码,根据指定的用户输入,试图删除文件中的一行。方法是

  • 将文件读入列表
  • 删除列表中的相关行(最好是在列表中阅读时?)
  • 重写文件 我想对第2和第3部分提供一些指导和意见,以及如何使用csv reader在python中执行这种简单的删除/编辑操作的最佳解决方案(对于初学者,出于教学/学习目的)

    代码

    """ ==============TASK
    1. Search for any given username
    2. Delete the whole row for that particular user
    
    e.g.
    Enter username: marvR
    >>The record for marvR has been deleted from file.
    """
    
    import csv
    
    #1. This code snippet asks the user for a username and deletes the user's record from file.
    
    updatedlist=[]
    with open("fakefacebook.txt",newline="") as f:
      reader=csv.reader(f)
      username=input("Enter the username of the user you wish to remove from file:")
      for row in reader: #for every row in the file
          if username not in updatedlist:
            updatedlist=row #add each row, line by line, into a list called 'udpatedlist'
            print(updatedlist)
    
     #delete the row for the user from the list?
    #overwrite the current file with the updated list?
    
    文件内容:

    username,password,email,no_of_likes
    marvR,pass123,marv@gmail.com,400
    smithC,open123,cart@gmail.com,200
    blogsJ,2bg123,blog@gmail.com,99
    
    更新

    """ ==============TASK
    1. Search for any given username
    2. Delete the whole row for that particular user
    
    e.g.
    Enter username: marvR
    >>The record for marvR has been deleted from file.
    """
    
    import csv
    
    #1. This code snippet asks the user for a username and deletes the user's record from file.
    
    updatedlist=[]
    with open("fakefacebook.txt",newline="") as f:
      reader=csv.reader(f)
      username=input("Enter the username of the user you wish to remove from file:")
      for row in reader: #for every row in the file
          if username not in updatedlist:
            updatedlist=row #add each row, line by line, into a list called 'udpatedlist'
            print(updatedlist)
    
     #delete the row for the user from the list?
    #overwrite the current file with the updated list?
    
    根据下面的回答,我有这个问题,但是当它覆盖文件时,它不能用列表正确地更新它,不知道为什么

    import csv
    def main():
        #1. This code snippet asks the user for a username and deletes the user's record from file.
        updatedlist=[]
        with open("fakefacebook.txt",newline="") as f:
          reader=csv.reader(f)
          username=input("Enter the username of the user you wish to remove from file:")
          for row in reader: #for every row in the file
              if row[0]!=username: #as long as the username is not in the row .......
                updatedlist=row #add each row, line by line, into a list called 'udpatedlist'
                print(updatedlist)
        updatefile(updatedlist)
    
    def updatefile(updatedlist):
        with open("fakefacebook.txt","w",newline="") as f:
            Writer=csv.writer(f)
            Writer.writerow(updatedlist)
            print("File has been updated")
    
    
    main()
    
    它似乎正确地打印了updatedfile(作为列表),因为它删除了输入的用户名。但在将其写入文件时,它只向文件打印一个用户名


    有什么想法让我可以接受最后的答案吗?

    使用
    csv
    模块,这样做应该可以帮助您。由于您已使用定义的列对表格数据进行结构化,因此应使用
    DictReader
    DictWriter
    对文件进行读写

    import csv
    
    with open('fakefacebook.txt', 'r+') as f:
        username = input("Enter the username of the user you wish "
                             "to remove from file:")
        columns = ['username', 'password', 'email', 'no_of_likes']
    
        reader = csv.DictReader(f, columns)
        filtered_output = [line for line in reader if line['username'] != username]
    
        f.seek(0)
        writer = csv.DictWriter(f, columns)
        writer.writerows(filtered_output)
        f.truncate()
    

    这将打开输入文件,过滤掉用户名等于要删除的所需用户名的任何条目,并将保留的条目写回输入文件,覆盖已有的条目。

    使用
    csv
    模块,您应该执行类似操作。由于您已使用定义的列对表格数据进行结构化,因此应使用
    DictReader
    DictWriter
    对文件进行读写

    import csv
    
    with open('fakefacebook.txt', 'r+') as f:
        username = input("Enter the username of the user you wish "
                             "to remove from file:")
        columns = ['username', 'password', 'email', 'no_of_likes']
    
        reader = csv.DictReader(f, columns)
        filtered_output = [line for line in reader if line['username'] != username]
    
        f.seek(0)
        writer = csv.DictWriter(f, columns)
        writer.writerows(filtered_output)
        f.truncate()
    

    这将打开输入文件,过滤掉用户名等于要删除的用户名的所有条目,并将保留的条目写回输入文件,覆盖已有的条目。

    如果用户名不在更新列表中:

    对我来说应该是:

    如果行[0]!=用户名:

    然后在第二个循环中,将updatedlist写入csv文件。 我会在阅读时亲自将所有内容写入另一个文件中,然后最终删除旧文件并替换为新文件,这使得它只循环一次

    编辑:

    updatedlist=row
    替换为
    updatedlist.append(row)
    :第一个表示用一行覆盖
    updatedlist
    ,第二个表示向其添加一行

    writerow
    写一行,然后给它一个行列表。 改用
    writerows
    ,您的书写功能将正常工作

    你几乎是一个人完成的,这是我的目标。
    其他一些答案已经为您提供了更好(更快、更干净…)的方法,所以我不会。

    如果用户名不在更新列表中:

    对我来说应该是:

    如果行[0]!=用户名:

    然后在第二个循环中,将updatedlist写入csv文件。 我会在阅读时亲自将所有内容写入另一个文件中,然后最终删除旧文件并替换为新文件,这使得它只循环一次

    编辑:

    updatedlist=row
    替换为
    updatedlist.append(row)
    :第一个表示用一行覆盖
    updatedlist
    ,第二个表示向其添加一行

    writerow
    写一行,然后给它一个行列表。 改用
    writerows
    ,您的书写功能将正常工作

    你几乎是一个人完成的,这是我的目标。
    其他一些答案已经为您提供了更好(更快、更干净…)的方法,因此我不会这样做。

    我推荐这种方法:

    with open("fakefacebook.txt", 'r+') as f:
        lines = f.readlines()
        f.seek(0)
    
        username = input("Enter the username of the user you wish to remove from file: ")
        for line in lines:
            if not username in line.split(',')[0]:  # e.g. is username == 'marvR', the line containing 'marvR' will not be written
                f.write(line)
    
        f.truncate()
    

    文件中的所有行都被读入
    。然后我用
    f.seek(0)
    返回文件的起始位置。此时,要求用户输入用户名,然后在写回文件之前使用用户名检查每一行。如果该行包含指定的用户名,则不会写入该行,从而“删除”该行。最后,我们使用
    f.truncate()
    删除多余的部分。我希望这会有帮助,如果你有任何问题,请不要犹豫

    我推荐这种方法:

    with open("fakefacebook.txt", 'r+') as f:
        lines = f.readlines()
        f.seek(0)
    
        username = input("Enter the username of the user you wish to remove from file: ")
        for line in lines:
            if not username in line.split(',')[0]:  # e.g. is username == 'marvR', the line containing 'marvR' will not be written
                f.write(line)
    
        f.truncate()
    

    文件中的所有行都被读入
    。然后我用
    f.seek(0)
    返回文件的起始位置。此时,要求用户输入用户名,然后在写回文件之前使用用户名检查每一行。如果该行包含指定的用户名,则不会写入该行,从而“删除”该行。最后,我们使用
    f.truncate()
    删除多余的部分。我希望这会有帮助,如果你有任何问题,请不要犹豫

    我试图坚持你的代码:(编辑:不优雅,但尽可能接近OPs代码)


    但我建议使用numpy或pandas,我试着坚持你的代码:(编辑:不优雅,但尽可能接近OPs代码)


    但我建议使用numpy或pandas,另外一个答案是:写入一个新文件,然后重命名它

    import csv
    import os
    
    def main():
        username = input("Enter the username of the user you wish to remove from file:")
        # check it's not 'username'!
    
        #1. This code snippet asks the user for a username and deletes the user's record from file.
        with open("fakefacebook.txt", newline="") as f_in, \
                open("fakefacebook.txt.new", "w", newline="") as f_out:
            reader = csv.reader(f_in)
            writer = csv.writer(f_out)
            for row in reader: #for every row in the file
                if row[0] != username: # as long as the username is not in the row
                    writer.writerow(row)
        # rename new file
        os.rename("fakefacebook.txt.new", "fakefacebook.txt")
    
    main()
    

    另一个答案是:写入一个新文件,然后重命名它

    import csv
    import os
    
    def main():
        username = input("Enter the username of the user you wish to remove from file:")
        # check it's not 'username'!
    
        #1. This code snippet asks the user for a username and deletes the user's record from file.
        with open("fakefacebook.txt", newline="") as f_in, \
                open("fakefacebook.txt.new", "w", newline="") as f_out:
            reader = csv.reader(f_in)
            writer = csv.writer(f_out)
            for row in reader: #for every row in the file
                if row[0] != username: # as long as the username is not in the row
                    writer.writerow(row)
        # rename new file
        os.rename("fakefacebook.txt.new", "fakefacebook.txt")
    
    main()
    

    如果有人使用了
    “marvR”
    作为密码怎么办?他们是否应该因此而被删除(谢谢flevinkelming-你能看到我的更新并提出最终解决方案吗-我就快到了。@计算错误你的行
    updatedlist=row
    应该是
    updatedlist.append(row)
    -对于您当前编写的内容,不包含
    用户名的最后一行将分配给
    更新列表
    ,该行是您当前正在写入文件的内容,而不是所有不包含用户名的行。如果有人使用了
    “marvR”,该怎么办
    作为他们的密码?他们应该因此而被删除吗?:(谢谢Flevincelming-你能看到我的更新并建议fina吗