gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:32:05 26 4
gpt4 key购买 nike

关于 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,您的书写功能将起作用。

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

关于python - 使用 csv 阅读器从文件中删除行并列出 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45303186/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com