Search code examples
python-3.xargparse

argparse, python3, can't use parsed file as file


I need to parse .txt file as argument for my script. And then split it by lines, turn it into list and print it.

parser = argparse.ArgumentParser()
parser.add_argument('textA', type=argparse.FileType('r'), nargs=1, default='textA.txt')
args = parser.parse_args()

textA = args.textA.read().split('\n')
print(textA)

But ends up with AttributeError: 'list' object has no attribute 'read' in console

I think I just don't know how to parse file properly


Solution

  • The narg parameter is the cause of the problem.

    This is the documentation that explains the usage of this parameter https://docs.python.org/3/library/argparse.html?highlight=argparse#nargs

    1. If you wish this arg to be optional and defaults to 'textA.txt', you should use nargs="?" in this case.
    2. If you wish to make this a mandatory field, change args.textA.read() to args.textA[0].read() and leave nargs=1 as is