尝试加密文本文件会导致类型错误

2024-09-28 16:44:49 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我的代码:

my_text= F = open("mytext.txt")
KEY=4
encoded= ""

for c in my_text:
    rem = (ord(c) - 97 + KEY) % 26
    encoded += chr(rem + 97)

print(encoded)

错误:

TypeError: ord() expected a character, but string of length 21 found

它返回上面的错误,但我不知道如何解决它。你知道吗


Tags: key代码textintxtformy错误
2条回答

您必须使用readlines并对文本文件中的任何新行执行其他循环。否则单线就好了。你知道吗

my_text= F = open("mytext.txt")
my_text = F.readlines()
KEY = 4 
encoded= ""
for c in my_text:
    for c1 in c:
        rem = (ord(c1) - 97 + KEY) % 26 
        encoded += chr(rem + 97)

print(encoded)

默认情况下,遍历文件会逐行检索数据。您可以使用^{}内置函数的两个参数以字节流的形式读入文件,如下所示。注意,这种方法将而不是一次将整个文件读入内存,就像使用^{}内置程序那样。你知道吗

KEY = 4
encoded = ""

with open("mytext.txt", 'rb') as my_text:
    # Using iter() like below causes it to quit when read() returns an
    # empty char string (which indicates the end of the file has been
    # reached).
    for c in iter(lambda: my_text.read(1), b''):
        rem = (ord(c) - 97 + KEY) % 26
        encoded += chr(rem + 97)

print(encoded)

相关问题 更多 >