I'm trying to read multiple files passed on the command line as arguments but also check if positional parameters are being passed to do something different when the positional parameter is set. For example if run python3 myprogram.py file1.txt file2.txt
the program just stores the files into a variable and loads another function, but if we run python3 myprogram.py -n file1.txt file2.txt
the program does something else. I'm using sys and argparse as the two libraries to solve this.
This is how I'm handling the parameters being passed..
def manin():
parser = ArgumentParser()
parser.add_argument("-d", "--default", dest="myFile", help="Open specified file")
args = parser.parse_args()
myFile = args.myFile
if myFile:
text = open(myFile)
counter = 0 # set a counter to 0
for line in text: #for each line in text if the " 200 " is found add 1 to the counter and repeat until done.
if re.findall(r"\s\b200\b\s", line):
counter += 1
print("\nTotal of (Status Code) 200 request:", counter, "\n")
else:
menu()
and this is how I'm loading all the file arguments passed to the program into a variable
allFileContents = ""
for arg in sys.argv[1:]:
try:
print("Loading Files ...." , sys.argv[1:])
myfile = open(arg, "r")
filecontents = myfile.readlines()
myfile.close()
allFileContents = allFilesContents + filecontents
return allFileContents
except OSError:
print("File could not be opened" + arg + ".")
I'm having trouble making sense of how would I combine the two together so it can perform both functions. Load the files into a variable and also check the positional parameters. Any tips or recommendation will be highly appreciated, I was told that using *args and **kwargs would be much easier but I haven't found anything online that handles files with *args and **kwargs. Thanks