2011-04-20 46 views
0

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

什麼問題?請不要在沒有提供信息的情況下將代碼扔在我們的頭上,代碼正在做什麼或應該做什麼。 – 2011-04-20 06:33:47

+0

idk =我不知道 – 2011-04-20 06:49:28

+0

你有沒有回溯?打印(decrypted_line)打印什麼? – joaquin 2011-04-20 07:15:51

回答

0

我能想到的2個軌道以遵循:

  • 使用raw_input,它返回一個字符串,而不是input返回一個函數(即無效您的測試userInput == "decrypt"和類似)
  • for line in in_file:就足以瀏覽一個文件,你不需要添加read_line = in_file.readline()