Reputation: 23
I am able to edit and add new entries but everytime i try to delete the row i search for, it wipes the whole files data.
I need it to just remove that row of data without losing the rest of the rows.
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
Upvotes: 0
Views: 370
Reputation: 87134
Change the section containing the for loop to this:
for row in f1:
if rid in row[0]:
found=True
print rid, "has been deleted from the database!"
else:
f2.writerow(row)
The changes:
rid
is not in row[0]
found
flag to False
The rest of the code also needs some work:
import program
to return to the login ????? That's not going to
work. Perhaps you should just return from the function.delete()
and the calling code which
relies on a file named temp.csv
being created. It would be much
better if delete()
performed the renaming of the temporary file itself.Upvotes: 0
Reputation: 255
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
Upvotes: 1
Reputation: 4449
You never actually write to the new csv file.
Look at the main filter/copy loop:
# 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` ...
So you'll end up with an empty output file ...
Upvotes: 1