Python文件加密(字典、文件和异常)

Python文件加密(字典、文件和异常),python,file,dictionary,exception,encryption,Python,File,Dictionary,Exception,Encryption,我试图创建一个程序,允许用户加密或解密文件。我只是不知道下一步该怎么办,另一个问题是,当我按enter键时,退出程序并不总是有效。这些是我需要使用的函数 def main(): menuSelection = displayMenuAndGetOption() if menuSelection == "Q": input("\nRun complete. Press the Enter key to exit."

我试图创建一个程序,允许用户加密或解密文件。我只是不知道下一步该怎么办,另一个问题是,当我按enter键时,退出程序并不总是有效。这些是我需要使用的函数

def main():

    menuSelection = displayMenuAndGetOption()
    
    if menuSelection == "Q":
        input("\nRun complete. Press the Enter key to exit.")
        
    elif menuSelection == "E":
        file = getFiles(menuSelection)
        
    elif menuSelection == "D":
        file = getFiles(menuSelection)
        
    else:
        print("\nError - invalid option.")
        input("\nRun complete. Press the Enter key to exit.")

def displayMenuAndGetOption():

    print("\nFile Encryption Program")

    print("\nE = Encrypt a file", "D = Decrypt a file", "Q = Quit the Program", sep = "\n")

    option = input("\nEnter menu selection (E, D, or Q): ").upper()

    return option

def getFiles(fileOption):

    while fileOption != "":
        try:
            if fileOption == "E":
                inputFile = input("\nEnter the file to ENCRYPT. Press Enter alone to abort: ")
                filetext = open(inputFile, "r")
            elif fileOption == "D":
                inputFile = input("\nEnter the file to DECRYPT. Press Enter alone to abort: ")
                filetext = open(inputFile, "r")
        except IOError:
            print("Error - that file does not exist. Try again.")
        else:
            newfile = input("Enter the output file name: ")
            outputFile = open(newfile, "w")
        fileOption
    return fileOption

def convert(inputFile, outputFile):

    # Encryption and decryption are inverse of one another
    CODE = {'A':')','a':'0','B':'(','b':'9','C':'*','c':'8',\
            'D':'&','d':'7','E':'^','e':'6','F':'%','f':'5',\
            'G':'$','g':'4','H':'#','h':'3','I':'@','i':'2',\
            'J':'!','j':'1','K':'Z','k':'z','L':'Y','l':'y',\
            'M':'X','m':'x','N':'W','n':'w','O':'V','o':'v',\
            'P':'U','p':'u','Q':'T','q':'t','R':'S','r':'s',\
            'S':'R','s':'r','T':'Q','t':'q','U':'P','u':'p',\
            'V':'O','v':'o','W':'N','w':'n','X':'M','x':'m',\
            'Y':'L','y':'l','Z':'K','z':'k','!':'J','1':'j',\
            '@':'I','2':'i','#':'H','3':'h','$':'G','4':'g',\
            '%':'F','5':'f','^':'E','6':'e','&':'D','7':'d',\
            '*':'C','8':'c','(':'B','9':'b',')':'A','0':'a',\
            ':':',',',':':','?':'.','.':'?','<':'>','>':'<',\
            "'":'"','"':"'",'+':'-','-':'+','=':';',';':'=',\
            '{':'[','[':'{','}':']',']':'}'}
    
    result = ''
    fileText = inputFile.read()
    inputFile.close()

    for eachchar in fileText:
        returnVal = CODE.get(eachchar,eachchar)
        result = result + returnVal
    outputFile.write(result)
    outputFile.close()

在这个片段中似乎有很多未完成的想法。首先,我建议在从文件启动程序时调用main函数。在底部添加:

if __name__ == '__main__':
    main()
在python中,在一个函数中打开文件,然后在堆栈更高的函数中关闭文件通常是不好的做法。您可以使用
os.path.exists
检查文件是否存在,并将输入和输出文件名的字符串作为元组返回

该函数的示例如下所示

import os
import sys

def getFiles(fileOption):
    msg = "\nEnter the file to {}. Press Enter alone to abort:".format('ENCRYPT' if fileOption == 'E' else 'DECRYPT')
    inputFile = input(msg)
    while(not os.path.exists(inputFile)):
        if(inputFile == ''):
            input("\nRun complete. Press the Enter key to exit.")
            sys.exit()
        print('Error - that file does not exist. Try again.')
        input(msg)
    outputFile = input('Enter the output file name: ')
    return inputFile, outputFile
现在应该调用getFiles为元组设置相应的值。即

input_filename, output_filename = getFiles(menuSelection)
现在更改convert函数,使其在上下文管理器中获取文件的文本,以及为了提高效率,将结果更改为列表并附加到列表中,这样您就不会每次要附加字符时都创建新字符串

def convert(inputFileName, outputFileName):

    # Encryption and decryption are inverse of one another
    CODE = {'A':')','a':'0','B':'(','b':'9','C':'*','c':'8',
            'D':'&','d':'7','E':'^','e':'6','F':'%','f':'5',
            'G':'$','g':'4','H':'#','h':'3','I':'@','i':'2',
            'J':'!','j':'1','K':'Z','k':'z','L':'Y','l':'y',
            'M':'X','m':'x','N':'W','n':'w','O':'V','o':'v',
            'P':'U','p':'u','Q':'T','q':'t','R':'S','r':'s',
            'S':'R','s':'r','T':'Q','t':'q','U':'P','u':'p',
            'V':'O','v':'o','W':'N','w':'n','X':'M','x':'m',
            'Y':'L','y':'l','Z':'K','z':'k','!':'J','1':'j',
            '@':'I','2':'i','#':'H','3':'h','$':'G','4':'g',
            '%':'F','5':'f','^':'E','6':'e','&':'D','7':'d',
            '*':'C','8':'c','(':'B','9':'b',')':'A','0':'a',
            ':':',',',':':','?':'.','.':'?','<':'>','>':'<',
            "'":'"','"':"'",'+':'-','-':'+','=':';',';':'=',
            '{':'[','[':'{','}':']',']':'}'}

    result = []
    fileText = ''
    with open(inputFileName, 'r') as fp:
        fileText = fp.read()

    for eachchar in fileText:
        returnVal = CODE.get(eachchar,eachchar)
        result.append(returnVal)
    with open(outputFileName, 'w') as fp:
        fp.write(''.join(result))

def转换(inputFileName,outputFileName):
#加密和解密是相反的
代码={'A':')'、'A':'0'、'B':'('、'B':'9'、'C':'*'、'C':'8',
"D":"D":"7","E":"6","F":"5",,
‘G’:‘美元’、‘G’:‘4’、‘H’:‘#’、‘H’:‘3’、‘I’:‘@’、‘I’:‘2’,
‘J’:‘Y’,‘J’:‘1’,‘K’:‘Z’,‘K’:‘Z’,‘L’:‘Y’,‘L’:‘Y’,
‘M’:‘X’,‘M’:‘X’,‘N’:‘W’,‘N’:‘W’,‘O’:‘V’,‘O’:‘V’,
‘P’:‘U’,‘P’:‘U’,‘Q’:‘T’,‘Q’:‘T’,‘R’:‘S’,‘R’:‘S’,
‘S’:‘R’,‘S’:‘R’,‘T’:‘Q’,‘T’:‘Q’,‘U’:‘P’,‘U’:‘P’,
‘V’:‘O’,‘V’:‘O’,‘W’:‘N’,‘W’:‘N’,‘X’:‘M’,‘X’:‘M’,
‘Y’:‘L’,‘Y’:‘L’,‘Z’:‘K’,‘Z’:‘K’,‘Y’:‘J’,‘1’:‘J’,
“@':'I','2':'I','H','3':'H','$':'G','4':'G',
“%”:“F”、“5”:“F”、“^”:“E”、“6”:“E”、“&”:“D”、“7”:“D”,
“*”:“C”、“8”:“C”、“(”:“B”、“9”:“B”、“)”:“A”、“0”:“A”,

'',',',',',',',',',',',' '>:'在Python中,变量和函数被命名为“代码> LoeCaseEx,带有下划线 <代码> CAMELCASE 使用上下文管理器来处理文件.我将认真考虑一些重构.例如,没有理由拥有加密功能(<代码>转换< /代码>)处理文件。我明天会发布你程序的重构版本。
def convert(inputFileName, outputFileName):

    # Encryption and decryption are inverse of one another
    CODE = {'A':')','a':'0','B':'(','b':'9','C':'*','c':'8',
            'D':'&','d':'7','E':'^','e':'6','F':'%','f':'5',
            'G':'$','g':'4','H':'#','h':'3','I':'@','i':'2',
            'J':'!','j':'1','K':'Z','k':'z','L':'Y','l':'y',
            'M':'X','m':'x','N':'W','n':'w','O':'V','o':'v',
            'P':'U','p':'u','Q':'T','q':'t','R':'S','r':'s',
            'S':'R','s':'r','T':'Q','t':'q','U':'P','u':'p',
            'V':'O','v':'o','W':'N','w':'n','X':'M','x':'m',
            'Y':'L','y':'l','Z':'K','z':'k','!':'J','1':'j',
            '@':'I','2':'i','#':'H','3':'h','$':'G','4':'g',
            '%':'F','5':'f','^':'E','6':'e','&':'D','7':'d',
            '*':'C','8':'c','(':'B','9':'b',')':'A','0':'a',
            ':':',',',':':','?':'.','.':'?','<':'>','>':'<',
            "'":'"','"':"'",'+':'-','-':'+','=':';',';':'=',
            '{':'[','[':'{','}':']',']':'}'}

    result = []
    fileText = ''
    with open(inputFileName, 'r') as fp:
        fileText = fp.read()

    for eachchar in fileText:
        returnVal = CODE.get(eachchar,eachchar)
        result.append(returnVal)
    with open(outputFileName, 'w') as fp:
        fp.write(''.join(result))