I have the following script -
import os, errno
import argparse
def removecompressed(filename):
try:
os.remove(filename)
print('Removing {}'.format(args.compressedfile))
except OSError as e: # this would be "except OSError, e:" before Python 2.6
print ('File {} does not exist in location {}!'.format(args.compressedfile, args.localpath))
if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory
raise # re-raise exception if a different error occured
def removeencrypted(filename):
try:
os.remove(filename)
print('Removing {}'.format(args.encryptedfile))
except OSError as e: # this would be "except OSError, e:" before Python 2.6
print ('File {} does not exist in location {}!'.format(args.encryptedfile, args.localpath))
if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory
raise # re-raise exception if a different error occured
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--localpath', type=str, default='', help="the path containing the files")
parser.add_argument('-c', '--compressedfile', type=str, default='', help="the compressed file to be deleted")
parser.add_argument('-e', '--encryptedfile', type=str, default='', help="the encrypted file to be deleted")
args = parser.parse_args()
removecompressed(args.localpath + args.compressedfile)
removeencrypted(args.localpath + args.encryptedfile)
But I want the -e and -c arguments to be optional. How would I go about doing this?
I understand this reply: Argparse optional positional arguments?
but the problem is that the def is parsing 2 strings together first to make the filename. If I remove one of the arguments it complains about adding a string and a none value.
edit - if I use all 3 arguments there's no problem. If I remove the -e or -c for example here I've removed the -e I get the following exception -
Traceback (most recent call last):
File "cleanup.py", line 35, in <module>
removeencrypted(args.localpath + args.encryptedfile)
TypeError: Can't convert 'NoneType' object to str implicitly
I've updated my arguments to include default=''