Skip to main content
 首页 » 编程设计

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

2025年05月04日13softidea

关于 SO 也有类似的问题,但没有一个涉及我需要的细节。

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

  1. 将文件读入列表
  2. 删除列表中的相关行(最好是在阅读列表时?)
  3. 覆盖文件。

我希望在第 2 和第 3 部分获得有关最佳解决方案(对于初学者,用于教学/学习目的)的一些指导和评论,以使用 csv 阅读器在 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 

更新

根据下面的答案,我有这个,但是当它覆盖文件时,它没有正确地用列表更新它,不知道为什么。

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

它似乎正确地打印了更新的文件(作为列表),因为它删除了输入的用户名。但是在将其写入文件时,它只会将一个用户名打印到文件中。

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

请您参考如下方法:

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

对我来说应该是:

if row[0] != 用户名:

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

编辑:

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

writerow 写一行,你给它一个行列表。 请改用 writerows,您的书写功能将起作用。

你几乎靠自己完成了这一切,这是我的目标。 其他一些答案已经为您提供了更好(更快、更清洁...)的方法,所以我不会。