Python文件路径验证:凯撒加密程序的输入容错优化需求
凯撒加密文件路径验证解决方案
问题修复说明
原代码未对文件路径做有效性校验,且存在部分逻辑瑕疵(如仅读取文件第一行、使用全局变量而非函数参数、追加写入导致内容混乱)。以下方案在保留核心加密逻辑的前提下,添加路径循环验证,并修正细节问题。
完整修正代码
def open_file(source_path: str): # 读取整个文件内容,而非仅第一行 with open(source_path, mode='r') as fd: return fd.read() def write_to_file(dest_path: str, content: str): # 使用w模式覆盖写入,避免追加旧内容 with open(dest_path, mode='w') as fd: fd.write(content) def validate_source_path() -> str: while True: path = input("Enter the name of the file including the message: ") try: # 尝试打开文件验证可读性 with open(path, 'r'): return path except FileNotFoundError: print(f"Error: 文件 '{path}' 不存在,请重新输入。") except PermissionError: print(f"Error: 无权限读取文件 '{path}',请重新输入。") except Exception as e: print(f"Error: 读取文件失败 - {str(e)},请重新输入。") def validate_dest_path() -> str: while True: path = input("Enter the name of the file where the encrypted message will be written: ") try: # 尝试打开文件验证可写性(支持创建新文件) with open(path, 'w'): return path except PermissionError: print(f"Error: 无权限写入文件 '{path}',请重新输入。") except Exception as e: print(f"Error: 写入文件失败 - {str(e)},请重新输入。") MODE_ENCRYPT = 1 def caesar(source: str, dest: str, steps, mode): alphabet = "abcdefghijklmnopqrstuvwxyzabcABCDEFGHIJKLMNOPQRSTUVWXYZABC" alpha_len: int = len(alphabet) new_data = "" file_content = open_file(source) for char in file_content: index = alphabet.find(char) if index == -1: new_data += char else: changed = index + steps if mode == MODE_ENCRYPT else index - steps changed %= alpha_len new_data += alphabet[changed] write_to_file(dest, new_data) return new_data # 获取并验证文件路径 source_path = validate_source_path() dest_path = validate_dest_path() # 验证密钥输入 while True: key = input("Enter the key: ") try: key = int(key) break except ValueError: print("Please enter a valid key: ") ciphered = caesar(source_path, dest_path, key, MODE_ENCRYPT)
关键修改点
- 路径验证逻辑:新增两个独立验证函数,通过
while循环持续提示输入,直到路径合法。分别针对源文件的可读性、目标文件的可写性做校验,并捕获不同异常给出明确提示。 - 文件读写优化:
open_file移除无用参数,改为读取整个文件内容,符合加密完整消息的需求。write_to_file改用w模式覆盖写入,避免重复加密时追加旧内容。
- 函数逻辑规范:
caesar函数使用传入的参数source/dest而非全局变量,避免逻辑混乱。
内容的提问来源于stack exchange,提问作者Juj
相关产品推荐
相关产品推荐

