我正在制作一个程序,它将通过偏移因子加密文件。但是我得到了这个错误:
Traceback (most recent call last):
File "Y:\computer science\programming\year 10\controlled assessment\code.py", line 40, in <module>
file1.write(chr(encode))
File "C:\Program Files\Python35\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\x88' in position 0: character maps to <undefined>
以下是代码的相关位:
if choice == '1':
a = open('saved.txt', 'w')
a.close()
file = open('sample.txt', 'r')
file = file.read()
thing = list(file)
for i in range(len(thing)):
encode = ord(thing[i])
encode = encode + offset
if encode > 177:
encode = encode - 177
print(encode)
file1 = open('saved.txt', 'a')
file1.write(chr(encode))
#file1.close()
file2 = open('saved.txt', 'r')
print(file2.read())
#file.close()
#file2.close()
但是当我将偏移因子设置得非常小(例如1或2)时,它就会起作用。
答案 0 :(得分:0)
ascii表不会达到177,而只会达到127。 只是将177改为127
答案 1 :(得分:0)
您正在尝试编写二进制数据(文本,一旦加密,只是字节,而不再是文本)。
以二进制模式打开文件并编写bytes
个对象:
for i in range(len(thing)):
encode = ord(thing[i])
encode = encode + offset
if encode > 177:
encode = encode - 177
print(encode)
with open('saved.txt', 'ab') as file1:
file1.write(bytes([encode]))
读取数据时,您必须这样做;也许打印出加密后的结果为hex:
with open('saved.txt', 'rb') as file2:
print(file2.read().hex())
如果你先创建一个bytearray()
对象 ,附加到那个,然后在最后写出整个数组,效率会更高。