I'm trying to delete from a file.
This is what I am trying to do.
1.importing Easygui
2.Put three modes plus quitting
Everything is working except deleting part. this is what I have
import easygui
filea = open('GroceryList.txt', 'a')
fr = open('GroceryList.txt', 'r')
filer = open('GroceryList.txt', 'r')
runinng = True
while runinng:
a = easygui.choicebox('Do you want to add, delete, or see your list?',
choices = ['add', 'delete', 'see', 'quit'])
if a == 'add':
ad = easygui.enterbox('What do you want to add')
filea.write(ad)
filea.write('\n')
filea.close()
filea = open('GroceryList.txt', 'a')
elif a == 'delete':
rn = easygui.enterbox('What are you going to delete?')
rl = fr.readlines()
for lines in fr:
if rn in lines:
line.split()
fr.close()
fr = open('GroceryList.txt', 'r')
elif a == 'see':
s = filer.readlines()
easygui.msgbox(s)
filer.close()
filer = open('GroceryList.txt', 'r')
elif a == 'quit':
runinng = False
filea.close()
fr.close()
filer.close()
The part that is not working is:
elif a == 'delete':
rn = easygui.enterbox('What are you going to delete?')
rl = fr.readlines()
if rn in fr:
line.remove()
fr.close()
fr = open('GroceryList.txt', 'r')
As others mentioned in the comments just providing a small script to clear out the doubts you may still have
fr = open('GroceryList.txt', 'r')
rl = fr.readlines()
new_list_to_keep_rows=[]
for row in rl:
#add rows to keep
new_list_to_keep_rows.append(row)
new_file = open('GroceryList_new.txt', 'w')# open file in write mode
for item in new_list_to_keep_rows:
new_file.write("%s\n" % item)
rename the file when you are sure you have everything.