Python文件读写及凯撒密码代码报错求助:源文件未自动创建
源文件不存在报错原因及代码修正
报错原因
你的read_file函数使用"r"模式打开文件,这个模式仅用于读取已存在的文件,一旦文件不存在就会触发FileNotFoundError。Python的读取模式不会自动创建文件,只有写入/追加类模式(如"w"、"a"、"w+")才会在文件不存在时自动创建。
代码修正方案
1. 处理源文件不存在的场景
如果希望源文件不存在时自动创建空文件,可修改read_file函数为以下形式,使用"a+"模式(支持读写,文件不存在则创建),并将文件指针移到开头读取内容:
def read_file(path): with open(path, "a+") as fd: fd.seek(0) # 将文件指针定位到文件开头 return fd.read()
2. 补全凯撒密码加密逻辑
你之前用'_'.join(text.split('0'))作为加密替代逻辑,这里补上标准的凯撒密码实现(仅对大小写英文字母加密,其他字符保持原样):
def caesar_cipher(text: str, shift: int) -> str: result = [] for char in text: if char.islower(): # 处理小写字母 shifted = ord(char) + shift if shifted > ord('z'): shifted -= 26 result.append(chr(shifted)) elif char.isupper(): # 处理大写字母 shifted = ord(char) + shift if shifted > ord('Z'): shifted -= 26 result.append(chr(shifted)) else: # 非字母字符直接保留 result.append(char) return ''.join(result)
3. 完整修正代码
def read_file(path): with open(path, "a+") as fd: fd.seek(0) return fd.read() def create_file(path, text): with open(path, "w") as fd: return fd.write(text) def caesar_cipher(text: str, shift: int) -> str: result = [] for char in text: if char.islower(): shifted = ord(char) + shift shifted = shifted - 26 if shifted > ord('z') else shifted result.append(chr(shifted)) elif char.isupper(): shifted = ord(char) + shift shifted = shifted - 26 if shifted > ord('Z') else shifted result.append(chr(shifted)) else: result.append(char) return ''.join(result) def caesar_encrypt(source: str, dest: str, shift: int = 3): text = read_file(source) encrypted_text = caesar_cipher(text, shift) # 如果仍需使用之前的替代逻辑,注释掉上面一行,启用下面这行 # encrypted_text = '_'.join(text.split('0')) create_file(dest, encrypted_text) # 调用示例 caesar_encrypt('wwww', 'w2.txt')
可选:强制读取已存在文件的处理
如果你的需求是必须读取已存在的源文件,可在read_file中添加异常捕获,明确提示用户:
def read_file(path): try: with open(path, "r") as fd: return fd.read() except FileNotFoundError: raise FileNotFoundError(f"源文件 {path} 不存在,请先创建该文件。")
内容的提问来源于stack exchange,提问作者Nare Avetisyan
相关产品推荐
相关产品推荐

