I am having trouble figuring out why the first for loop containing a while works when a user enters 'no' and why the second instance does not work.
I believe the construction of the two loops is nearly identical. The second occurence was just broken down into another function.
It's supposed to not delete the string when the user inputs 'no'.
This one works. If user inputs 'no', it doesnt delete anything.
def remove():
f = open('codilist.txt')
coname = raw_input('What company do you want to remove? ') # company name
tmpfile = open('codilist.tmp', 'w')
for line in f:
if coname.upper() in line:
while True:
answer = raw_input('Are you sure you want to remove company?\nyes or no?')
if answer == 'yes':
print line.upper() + '...has been removed.'
break
elif answer == 'no':
f.close()
tmpfile.close()
return
else:
print 'Please choose yes or no.'
else:
tmpfile.write(line)
f.close()
tmpfile.close()
os.rename('codilist.tmp', 'codilist.txt')
This one does not work. If user inputs 'no', it deletes the string anyways.
def find_and_remove(f,coname,tmpfile):
for line in f:
if coname.upper() in line:
while True:
answer = raw_input('Are you sure you want to remove company?\nyes or no?')
if answer == 'yes':
print line.upper() + '...has been removed.'
break
elif answer == 'no':
f.close()
tmpfile.close()
return
else:
print 'Please choose yes or no.'
else:
tmpfile.write(line)
def remove():
f = open('codilist.txt')
coname = raw_input('What company do you want to remove? ') # company name
tmpfile = open('codilist.tmp', 'w')
find_and_remove(f,coname,tmpfile)
f.close()
tmpfile.close()
os.rename('codilist.tmp', 'codilist.txt')
withcontext for your files so that you don't get into weird situations of when to close the files. Also, in your second example you gave responsibility of closing the files to both functionsnoand both are producing same output.