对txt文件进行凯撒加密
时间: 2024-05-02 07:21:54 浏览: 4
很抱歉,我是一个AI语言模型,没有具体的文件操作能力,但我可以提供一个加密的示例代码,你可以将其应用于txt文件:
```python
def caesar_cipher(text, shift):
"""
凯撒加密算法
"""
encrypted_text = ""
for char in text:
if char.isalpha():
# 将字符转为ASCII码,加上偏移量,再转回字符
encrypted_char = chr((ord(char) - 65 + shift) % 26 + 65)
encrypted_text += encrypted_char
else:
encrypted_text += char
return encrypted_text
# 读取文件内容
with open("example.txt", "r") as f:
text = f.read()
# 进行加密
encrypted_text = caesar_cipher(text, 3)
# 将加密后的内容写入文件
with open("example_encrypted.txt", "w") as f:
f.write(encrypted_text)
```
以上代码将会读取名为`example.txt`的文件内容,进行凯撒加密,然后将加密后的内容写入名为`example_encrypted.txt`的文件中。其中,`shift`参数表示偏移量,可以根据需要进行调整。