如何修改两段Python代码以实现文本文件的加密与解密?
需求:修改文本加密/解密脚本以支持文件操作
原脚本仅能处理输入的单行字符串,现需修改为读取整个文本文件内容进行加密/解密,并将结果写入指定输出文件。
原加密脚本(项目1):
message = input("Enter a message: ") dValue = int(input("Enter distance value: ")) code = "" for ch in message: ordvalue = ord(ch) cipherValue = ordvalue + dValue code += chr(cipherValue) print() print(code)
原解密脚本(项目2):
coded_text = input("Enter a coded text: ") dValue = int(input("Enter distance value: ")) code = "" for ch in coded_text: ordvalue = ord(ch) cipherValue = ordvalue - dValue code += chr(cipherValue) print() print(code)
程序运行界面示例:
Enter the input file name: encrypted.txt Enter the output file name: a Enter the distance value: 3
修改后的加密脚本
# 获取文件路径与偏移量 input_filename = input("Enter the input file name: ") output_filename = input("Enter the output file name: ") dValue = int(input("Enter the distance value: ")) # 读取输入文件全部内容 with open(input_filename, 'r', encoding='utf-8') as infile: content = infile.read() # 执行凯撒加密逻辑 code = "" for ch in content: ordvalue = ord(ch) cipherValue = ordvalue + dValue code += chr(cipherValue) # 将加密结果写入输出文件 with open(output_filename, 'w', encoding='utf-8') as outfile: outfile.write(code) print(f"加密完成,结果已写入 {output_filename}")
修改后的解密脚本
# 获取文件路径与偏移量 input_filename = input("Enter the input file name: ") output_filename = input("Enter the output file name: ") dValue = int(input("Enter the distance value: ")) # 读取加密文件全部内容 with open(input_filename, 'r', encoding='utf-8') as infile: coded_content = infile.read() # 执行凯撒解密逻辑 code = "" for ch in coded_content: ordvalue = ord(ch) cipherValue = ordvalue - dValue code += chr(cipherValue) # 将解密结果写入输出文件 with open(output_filename, 'w', encoding='utf-8') as outfile: outfile.write(code) print(f"解密完成,结果已写入 {output_filename}")
关键修改说明
- 替换输入源:用
open()结合with语句(自动管理文件关闭)读取整个文件内容,替代原有的单行字符串输入逻辑。 - 保留核心算法:原凯撒密码的ASCII码偏移计算逻辑完全保留,仅将处理对象从输入字符串改为文件内容。
- 结果持久化:将加密/解密后的内容写入指定文件,而非仅在控制台打印。
内容的提问来源于stack exchange,提问作者Rep
相关产品推荐
相关产品推荐

