0

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

Katz
  • 826
  • 3
  • 19
  • 40
  • 1
    You can do all of what you want with the ArgumentParser, don't know where the problem is. You are basically looking for `parser.add_argument('file', type=argparse.FileType('r'), nargs='+')` – user1767754 Nov 23 '17 at 04:44
  • sorry I didn't mean to add argparse since it doesn't work in python3 @user1767754 I meant ArgParser – Katz Nov 23 '17 at 04:49
  • I'm working with python3 only @Blurp – Katz Nov 23 '17 at 04:50
  • I was confused because argparse _does_ work on Python 3: https://docs.python.org/3/library/argparse.html –  Nov 23 '17 at 04:50
  • my mistake, I was thinking of optparse for some odd reason. @Blurp – Katz Nov 23 '17 at 04:56
  • nargs = "+" allows any amount of argument to be passed? @user1767754 – Katz Nov 23 '17 at 04:57

0 Answers0