Python while循环逻辑异常、文件删除功能失效问题排查
Python文本替换程序交互逻辑异常修复
问题现象
程序基础功能为读取henryTheSquareEaredCat.txt文件,将文本中全小写的square替换为pentagon、首字母大写的Square替换为Pentagon,替换完成后将内容写入新文件henryThePentagonEaredCat.txt,目前文本替换功能运行正常,但新增的用户确认逻辑存在两处异常:
- 输入
N或n时,新生成的文件不会被删除,程序直接结束 - 输入
xyz这类非Y/N的无效内容时,程序不会按设计重新进入循环提示重试,直接终止运行
存在问题的原始代码
import os file = open('henryTheSquareEaredCat.txt', mode = 'r') newLines = [] for line in file: if 'square' in line : newLine = line.replace('square', 'pentagon') newLines.append(newLine) elif 'Square' in line: newLine = line.replace('Square', 'Pentagon') newLines.append(newLine) else: newLines.append(line) file.close() print(newLines) with open('henryThePentagonEaredCat.txt', mode='w') as newFile: for newLine in newLines: newFile.write(newLine) newFile.close() correct = False while not correct: keep = input('Would you like to keep the newly created file(Y or N)?') if keep == 'y' or 'Y': correct = True elif keep == 'n' or 'N': os.remove('henryThePentagonEaredCat.txt') print('The newly created file was successfully deleted') correct = True else: print('That is not a valid entry please try again')
问题根因
两处异常来自同一个逻辑写法错误:
条件判断中if keep == 'y' or 'Y'、elif keep == 'n' or 'N'的写法不符合Python逻辑运算规则。or会分别计算两侧表达式的布尔值,非空字符串的布尔值恒为True,因此第一个判断条件等价于(keep == 'y') or True,无论用户输入什么内容,都会直接命中第一个if分支,将correct设为True退出循环,后续的删除文件逻辑、无效输入重试逻辑永远不会触发。
修复后代码
import os file = open('henryTheSquareEaredCat.txt', mode = 'r') newLines = [] for line in file: if 'square' in line : newLine = line.replace('square', 'pentagon') newLines.append(newLine) elif 'Square' in line: newLine = line.replace('Square', 'Pentagon') newLines.append(newLine) else: newLines.append(line) file.close() print(newLines) with open('henryThePentagonEaredCat.txt', mode='w') as newFile: for newLine in newLines: newFile.write(newLine) correct = False while not correct: keep = input('Would you like to keep the newly created file(Y or N)?') if keep.lower() == 'y': correct = True elif keep.lower() == 'n': os.remove('henryThePentagonEaredCat.txt') print('The newly created file was successfully deleted') correct = True else: print('That is not a valid entry please try again')
修复说明
- 修正条件判断逻辑:将用户输入统一转为小写后再做匹配,既修复了判断恒真的问题,也省去了分别匹配大小写的冗余代码
- 移除冗余的
newFile.close()调用:with上下文管理器会在代码块执行结束后自动关闭打开的文件,不需要手动执行关闭操作
内容的提问来源于stack exchange,提问作者Z. Young
相关产品推荐
相关产品推荐

