Python:将Casear密码和柱状转置密码的加密输出写入.txt文件

时间:2015-10-27 20:04:41

标签: python powershell encryption

我希望这很容易解决。我在Windows Powershell中使用Python获得的错误如下:

回溯(最近一次调用最后一次):文件" [filename.py]",第66行,在 main(密文)NameError:name' ciphertext'未定义

我的代码:

def main():
# cipherOne contains encrypted Cesear cipher
 myMessage = cipherOne
 ciphertext = encryptMessage(key, myMessage)

 # Print the encrypted string in ciphertext to the screen, with
 # a | (called "pipe" character) after it in case there are spaces at
 # the end of the encrypted message.
 print(ciphertext)

def encryptMessage(key, message):
 # Each string in ciphertext represents a column in the grid.
 ciphertext = [''] * key

 # Loop through each column in ciphertext.
 for col in range(key):
     pointer = col

     # Keep looping until pointer goes past the length of the message.
     while pointer < len(message):
         # Place the character at pointer in message at the end of the
         # current column in the ciphertext list.
         ciphertext[col] += message[pointer]

         # move pointer over
         pointer += key

 # Convert the ciphertext list into a single string value and return it.
 return ''.join(ciphertext)

 # call main() function.

 if __name__ == '__main__':
  main()

 target = open (filenamenew, 'a')

 target.write(ciphertext) #the error

 target.close()

我可以将密文中的加密字符串打印到屏幕上,没有任何问题,但无法解决如何通过此错误,我可以将密文附加到.txt文件。

2 个答案:

答案 0 :(得分:1)

RobertB是对的。这是确切的代码修复:

只需将“main()”行更改为“ciphertext = main()”,您的代码就可以正常工作。你的函数已经返回了文本;你现在就把它扔掉,不要指定任何变量来获取返回值。

答案 1 :(得分:0)

按照RobertB的建议,将密文返回到例程解决了这个问题。