【问题标题】:Python File Encryption (Dictionaries, Files, and Exception)Python 文件加密(字典、文件和异常)
【发布时间】:2020-03-19 16:53:48
【问题描述】:

我正在尝试创建一个程序来允许用户加密或解密文件。我只是不知道下一步该做什么,另一个问题是当我按下回车键时退出程序并不总是有效。这些是我必须使用的功能。

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()

这就是它的样子。

样品运行

File Encryption Program

E = Encrypt a file
D = Decrypt a file
Q = Quit the program

Enter menu selection (E, D, or Q): x
Error - Invalid option.

Run complete. Press the Enter key to exit. 

File Encryption Program

E = Encrypt a file
D = Decrypt a file
Q = Quit the program

Enter menu selection (E, D, or Q): e

Enter the file to ENCRYPT. Press Enter alone to abort: filedoesnotexist.txt 
Error - that file does not exist. Try again.

Enter the file to ENCRYPT. Press Enter alone to abort: filetoencrypt.txt 
Enter the output file name: encryptedfile.txt

Run complete. Press the Enter key to exit.

File Encryption Program

E = Encrypt a file
D = Decrypt a file
Q = Quit the program

Enter menu selection (E, D, or Q): d

Enter the file to DECRYPT. Press Enter alone to abort: encryptedfile.txt 
Enter the output file name: decryptedfile.txt

Run complete. Press the Enter key to exit.

【问题讨论】:

  • 在 Python 中,变量和函数被命名为 lowercase_with_underscores 而不是 camelCase
  • 使用上下文管理器来处理文件。我会认真考虑一些重构。例如,没有理由让您的加密函数 (convert) 处理文件。明天我会尝试发布你的程序的重构版本。

标签: python file dictionary exception encryption


【解决方案1】:

这个sn-p似乎还有很多未完成的想法。首先,我建议您在从文件启动程序时调用您的 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)

现在更改您的转换函数,使其在上下文管理器中获取文件的文本,以及为了提高效率,将您的结果更改为列表并附加到列表中,这样您就不会每次都创建新字符串想追加一个字符

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))

【讨论】:

    猜你喜欢
    • 2012-05-22
    • 1970-01-01
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 1970-01-01
    • 2014-06-13
    • 2018-01-11
    相关资源
    最近更新 更多