用户输入加密/解密

时间:2011-04-20 06:29:23

标签: python encryption

Idk为什么这不输出到文件,任何想法或帮助?

def encrypt(text, key):
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    text = text.lower()
    cipherText = ""
    for ch in text:
        idx = alphabet.find(ch)
        cipherText = cipherText + key[idx]
    return cipherText

def decrypt(cipherText, key):
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    cipherText = cipherText.lower()
    text = ""
    for ch in cipherText:
        idx = key.find(ch)
        text = text + alphabet[idx]
    return text

def main():
    userInput = input("Operation (encrypt, decrypt, exit): ")
    while(userInput != "exit"):
        if(userInput == "encrypt"):
            in_file = open(input("Input file name: "), 'r')
            out_file = open(input("Output file name: "), 'w')
            password = input("Password: ")
            for line in in_file:
                read_line = in_file.readline()
                encrypted_line = encrypt(read_line, password)
                out_file.write(encrypted_line)
                print(encrypted_line)
            in_file.close()
            out_file.close()

        elif(userInput == "decrypt"):
            in_file = open(input("Input file name: "), 'r')
            out_file = open(input("Output file name: "), 'w')
            password = input("Password: ")
            for line in in_file:
                read_line = in_file.readline()
                decrypted_line = decrypt(read_line, password)
                out_file.write(decrypted_line)
                print(decrypted_line)
            in_file.close()
            out_file.close()

        else:
            print("Invalid choice!")
        userInput = input("Operation (encrypt, decrypt, exit): ")

main()

1 个答案:

答案 0 :(得分:0)

我可以想到要跟踪的两首曲目:

  • 使用raw_input,它返回一个字符串,而不是input,它返回一个函数(使您的测试userInput == "decrypt"无效){/ li>
  • for line in in_file:足以浏览文件,您无需添加read_line = in_file.readline()