i'm trying to access multiple .txt files with argparse and i've stumbled across a problem which i can't put my head around.
    parser = argparse.ArgumentParser()
    parser.add_argument('filename', nargs='+'. type=argparse.FileType('r'))
    args = parser.parse_args()
    with open(args.filename, 'r') as files:
         #do stuff to files
and i'm trying to access with
EDIT:
python3 script.py file1.txt file2.txt
But i'm getting an error as such:
Traceback (most recent call last):
  File "script.py", line 34 in <module>
    with open(args.filename, 'r') as files:
TypeError: expected str, bytes or os.PathLike objects, not list
I somewhat know what that means, but i just can't put my finger on what to do next.
From documentation nargs:
'+'. Just like '*', all command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least one command-line argument present.
So, If you want to open multiple files, u have to iter through your list with args. For example:
parser = argparse.ArgumentParser()    
parser.add_argument('filename', nargs='+')
args = parser.parse_args()
for file_name in args.filename:
    with open(file_name, 'r') as files:
        <do your code here>
        # a = files.read()
        # print(a)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With