如何修改Encrypt、Decrypt脚本实现整份文本文件的加密解密
加解密脚本修改方案
现有代码核心问题
- Encrypt.py 仅接收用户直接输入的短文本做加密,未读取输入文件内容、也未将加密结果写入指定输出文件
- Decrypt.py 误将输入的文件名字符串当做加密内容处理,未读取输入文件内容、也未将解密结果写入指定输出文件
修改后的Encrypt.py代码
""" File: encrypt.py Project 4.3 Encrypts a text file. The inputs are the names of the input file and the output file and the distance value. The encrypted code is witten to a new file. """ input_file = input("Enter the input file name: ") output_file = input("Enter the output file name: ") distance = int(input("Enter the distance value: ")) # 读取输入文件明文内容 with open(input_file, 'r', encoding='utf-8') as f: plainText = f.read() code = "" for ch in plainText: # 仅处理小写字母,其余字符原样保留 if ch.islower(): ordValue = ord(ch) cipherValue = ordValue + distance if cipherValue > ord('z'): cipherValue = ord('a') + distance - \ (ord('z') - ordValue + 1) code += chr(cipherValue) else: code += ch # 将加密结果写入输出文件 with open(output_file, 'w', encoding='utf-8') as f: f.write(code)
修改后的Decrypt.py代码
""" File: decrypt.py Project 4.3 Decrypts a file of encrypted text. and prints the result. The other input is the distance value. """ input_file = input("Enter the input file name: ") output_file = input("Enter the output file name: ") distance = int(input("Enter the distance value: ")) # 读取输入文件加密内容 with open(input_file, 'r', encoding='utf-8') as f: code = f.read() plainText = '' for ch in code: # 仅处理小写字母,其余字符原样保留 if ch.islower(): ordValue = ord(ch) cipherValue = ordValue - distance if cipherValue < ord('a'): cipherValue = ord('z') - (distance - \ (ordValue - ord('a')) - 1) plainText += chr(cipherValue) else: plainText += ch # 将解密结果写入输出文件 with open(output_file, 'w', encoding='utf-8') as f: f.write(plainText)
说明:当前逻辑默认仅处理小写字母,其余字符(大写、空格、标点、数字等)会原样保留,若需要支持其他字符的加解密,可自行调整字符范围判断规则。
内容的提问来源于stack exchange,提问作者chiggywiggy
相关产品推荐
相关产品推荐

