开发者

encryption/decryption with user input

Idk why this is not outputing to the file, any ideas or help?

def encrypt(text, key):
    alphabet = "abcdefghijklmnopqrstuvwx开发者_JS百科yz"
    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()


I can think of 2 tracks to be followed:

  • use raw_input, which returns a string, instead of input that returns a function (that invalidates your tests userInput == "decrypt" and similar)
  • for line in in_file: is enough to browse a file, you don't need to add read_line = in_file.readline()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜