用户输入的加解密

0 投票
1 回答
2261 浏览
提问于 2025-04-16 16:05

我不知道为什么这个没有输出到文件里,有什么想法或者帮助吗?

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

我想到有两种方法可以解决这个问题:

  • 使用 raw_input,它会返回一个字符串,而不是 input,后者返回的是一个函数(这样会让你的测试 userInput == "decrypt" 之类的失效)
  • 使用 for line in in_file: 就足够了,这样可以遍历文件,你不需要再加 read_line = in_file.readline() 这一行

撰写回答