我无法弄清楚为什么当用户输入“否”时第一个包含 while 的 for 循环有效,以及为什么第二个实例无效。
我相信这两个循环的构造几乎相同。第二次出现只是分解为另一个功能。
当用户输入“否”时,它应该不会删除字符串。
这个有效。如果用户输入“否”,它不会删除任何内容。
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')
这个不行。如果用户输入“否”,它无论如何都会删除该字符串。
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')