python编写程序实现移位密码和文件读写。加密时:读取明文文件(小写字母),键盘输入密钥(一个参数),结果保存为密文文件(大写字母)
时间: 2024-01-23 07:04:03 浏览: 26
下面是完整的代码实现:
```python
def shift_encrypt(plaintext, key):
ciphertext = ""
for char in plaintext:
if char.islower():
ciphertext += chr((ord(char) - 97 + key) % 26 + 65)
else:
ciphertext += char
return ciphertext
def shift_file_encrypt(input_file, output_file, key):
with open(input_file, "r") as f:
plaintext = f.read()
ciphertext = shift_encrypt(plaintext, key)
with open(output_file, "w") as f:
f.write(ciphertext)
def test_shift_file_encrypt():
input_file = "plaintext.txt"
output_file = "ciphertext.txt"
key = 3
with open(input_file, "w") as f:
f.write("hello world")
shift_file_encrypt(input_file, output_file, key)
with open(output_file, "r") as f:
ciphertext = f.read()
assert ciphertext == "KHOOR ZRUOG"
print("All tests passed")
if __name__ == "__main__":
test_shift_file_encrypt()
```
这个程序首先定义了 `shift_encrypt` 和 `shift_file_encrypt` 两个函数,分别用于加密单个字符串和整个文件。然后定义了一个测试函数 `test_shift_file_encrypt`,用于测试加密函数是否正常工作。
在 `test_shift_file_encrypt` 中,我们首先创建一个明文文件,然后调用 `shift_file_encrypt` 函数进行加密,最后读取密文文件并检查是否正确。
运行程序后,如果一切正常,会输出 "All tests passed"。你可以将明文文件命名为 `plaintext.txt`,将密文文件命名为 `ciphertext.txt`,然后在命令行中输入 `python filename.py` 来运行程序。在运行程序时,会要求你输入密钥,输入后程序会自动加密明文文件并保存到密文文件中。