我能夠編輯和添加新條目,但是每次我嘗試刪除我搜索的行時,它將刪除整個文件數據。如何獲取python刪除我從csv文件中搜索的行
我需要它只是刪除該行數據而不會丟失其餘的行。
import csv,os,sys
def helper(file):
o=csv.reader(open(file,"r"))
for row in o:
print row
def delete(filename):
found=False
f1=csv.reader(open(filename,'r'))
f2=csv.writer(open("temp.csv",'a'))
rid=raw_input("Enter name to find record:")
for row in f1:
if rid in row[0]:
found=True
f2.writerow()
print rid, "has been deleted from the database!"
else:
found=False
if found==False:
print "That name isn't in our database!"
z=raw_input("Please enter 1 to retry, 2 to return to log in, or 3 to close program:")
if z=="1":
delete(filename)
if z=="2":
import program
if z=="3":
exit
helping=raw_input("Do you require any help with using this feature?Type y for yes or just hit enter to continue:")
if helping=="y":
helper('deletehelp.txt')
delete("custdet.csv")
os.remove("custdet.csv")
os.rename("temp.csv","custdet.csv") #This is the file rename that I mentioned above.
restart=raw_input("Would you like to return to the main menu? Please type Y or just hit enter to exit:")
if restart=="y":
import program
else: exit
也許你的f2.writerow()應該在if語句之外!是的,它也是空的。 – AnnShress
你能告訴我你的意思嗎? –
如果你想刪除該行,該用戶輸入,你當然不想把它寫到你的新文件!所以它應該在__if__塊之外。 – AnnShress