2016-12-13 34 views
0

我正在制作一个程序,它将通过偏移因子对文件进行加密。但是,我得到这个错误:我在编码程序中出现无法解释的错误

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

我不是qiute肯定这个问题是如何与这个问题相同的 –

回答

0

ASCII表不走高达177,而只上升到127只 昌河177 127

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])) 

你必须做的时候您的数据是相同的;也许是打印出来的加密结果为十六进制:

with open('saved.txt', 'rb') as file2: 
    print(file2.read().hex()) 

它会更有效,如果你创建了一个bytearray()对象第一,追加到这一点,那么写出来末整个阵列。

相关问题