下面是我的代码:
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
它返回上面的错误,但我不知道如何解决。
最佳答案
默认情况下,遍历文件会逐行检索数据。您可以使用iter(callable, sentinel)
内置函数中的两个参数以字节流的形式读取文件,如下所示。请注意,这种方法不会一次将整个文件读入内存,就像使用内置readlines()
之类的操作一样。
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)