1

I am writing a python file that can encrypt and decrypt text files with Caesar cypher via python. This is the code I have been writing:

import sys
import argparse
import string


parser = argparse.ArgumentParser()
parser.add_argument("-i", dest="filein", help="input file")
parser.add_argument("-o", dest="fileout", help="output file")
parser.add_argument("-k", dest="keyin", help="key", type=int)
parser.add_argument("-m", dest="modein", help="mode", type=str) #e or d


# parse our arguments
args = parser.parse_args()
filein = args.filein
fileout = args.fileout
keyin = args.keyin
modein = args.modein



def cipher_cipher_using_lookup(text, key, characters = string.printable, mode = args.modein):
    if key <=0 or key >(len(string.printable)-1):
        print("The key must be between 1 and 99 inclusive")
        return None
        
    n = len(characters)

    if mode == "e" or mode == "E":
        key = key -0

    elif mode == "d" or mode == "D":
        key = n - key

    else:
        print("Invalid mode input. Input either 'e' or 'd'. Case insensitive")
    


    table = str.maketrans(characters, characters[key:]+characters[:key])
    translated_text = text.translate(table)
    return translated_text

def fileCipher(filein, fileout, keyin, modein):
    with open (args.filein, "r") as f_in:
        with open(args.fileout, "w") as f_out:
            for line in f_in:
                lineNew = cipher_cipher_using_lookup(line, key = args.keyin, mode = args.modein) #no characters argument
                
                if args.modein != "e" and args.modein != "E" and args.modein != "d" and args.modein != "D":
                    break
                
                f_out.write(lineNew)
    # print("The file {} has been translated successfully and saved to {}".format(filein, fileout))


fileCipher(filein, fileout, keyin, modein)

When invalid keys outside of the range 1 to 99 (e.g. negative numbers, 0, numbers larger than 99) I would only want the error message I have created: The key must be between 1 and 99 inclusive to be outputted. However, I get this instead:

The key must be between 1 and 99 inclusive
Traceback (most recent call last):

  File "[*the python script filepath*]", line 63, in <module>

    fileCipher(filein, fileout, keyin, modein)

  File "[*the python script filepath*]", line 59, in fileCipher

    f_out.write(lineNew)

TypeError: write() argument must be str, not None

Removing return None from cipher_cipher_using_lookup() will only result in a massive repetition of The key must be between 1 and 99 inclusive, which is undesired as well.

How do I only output The key must be between 1 and 99 inclusive when an invalid key is given?

Noob
  • 71
  • 9

0 Answers0