2016-01-23 41 views
0

我能夠編輯和添加新條目,但是每次我嘗試刪除我搜索的行時,它將刪除整個文件數據。如何獲取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 
+0

也許你的f2.writerow()應該在if語句之外!是的,它也是空的。 – AnnShress

+0

你能告訴我你的意思嗎? –

+0

如果你想刪除該行,該用戶輸入,你當然不想把它寫到你的新文件!所以它應該在__if__塊之外。 – AnnShress

回答

1
import csv,os,sys 

def helper(file): 
    o = csv.reader(open(file,"r")) 
    for row in o: 
     print row 

def delete(filename): 
    f1 = csv.reader(open(filename,'r')) 
    f2 = csv.writer(open("temp.csv",'a')) 
    rid = raw_input("Enter name to find record:") 
    found = False 
    for row in f1: 
     if rid not in row[0]: 
      f2.writerow(row) 
     else: 
      found = True 
      print rid, "has been deleted from the database!" 

    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 
1

你從來沒有真正寫入新的csv文件。

看主過濾器/複製循環:

# for every row in the input file 
for row in f1: 
     # Is this the/a record to delete? 
     if rid in row[0]: 
      # yes! 
      found=True 
      # then we do not write anything to the output file (???) 
      f2.writerow() 
      print rid, "has been deleted from the database!" 
     # no else part, so no nothing gets done with 
     # the input row `row` ... 

所以你用一個空的輸出文件結束了......

0

更改包含for循環到此節:

for row in f1: 
     if rid in row[0]: 
      found=True 
      print rid, "has been deleted from the database!" 
     else: 
      f2.writerow(row) 

的變化:

  • 其實寫的行如果ridrow[0]
  • 不要found標誌重置爲False

的代碼的其餘部分還需要一些工作:

  • 遞歸不是處理重試的最佳方法,而是使用循環。
  • import program返回登錄?????這不是 的工作。也許你應該從函數返回。
  • delete()和 依賴名爲temp.csv的文件被創建的調用代碼之間有耦合。如果delete()執行臨時文件本身的重命名,那麼將會更好 。