在SO上也有類似的問題,但沒有涉及我需要的細節。使用csv閱讀器從列表中刪除行並列出python
我有以下代碼,試圖根據指定的用戶輸入刪除文件中的一行。該方法是
- 讀取文件到列表
- 刪除列表中的相關行(理想情況下,而列表中的閱讀?)
- 過寫文件。
對於最好的解決方案(對於初學者,用於教學/學習目的),我希望得到一些指導和評論,以便在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,[email protected],400
smithC,open123,[email protected],200
blogsJ,2bg123,[email protected],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()
它似乎正確地打印更新文件(作爲列表),因爲它刪除了輸入的用戶名。但是在寫入文件時,它只會向文件打印一個用戶名。
有什麼想法,我可以接受最終答案?
最簡單的答案 - 輝煌的感謝!如果行[0]!=用戶名:工作。你還可以添加你的答案,包括最有效/簡單的方式,然後寫入文件(你的覆蓋建議?) – MissComputing
如果你能看到我的更新的問題 - 並回答它,我可以接受你的答案,因爲我已經使用了一半。謝謝 – MissComputing
編輯,希望它有幫助。 –