How to get filename with argparse while specifying type=FileType(...) for this argument

17,057

Yes, use the .name attribute on the file object.

Demo:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--sqlite-file', type=argparse.FileType('r'))
_StoreAction(option_strings=['--sqlite-file'], dest='sqlite_file', nargs=None, const=None, default=None, type=FileType('r'), choices=None, help=None, metavar=None)
>>> args = parser.parse_args(['--sqlite-file', '/tmp/demo.db'])
>>> args.sqlite_file
<_io.TextIOWrapper name='/tmp/demo.db' mode='r' encoding='UTF-8'>
>>> args.sqlite_file.name
'/tmp/demo.db'
Share:
17,057

Related videos on Youtube

jack_kerouac
Author by

jack_kerouac

Updated on June 04, 2022

Comments

  • jack_kerouac
    jack_kerouac almost 2 years

    Using the type parameter of the argparse.add_argument method, you can require an argument to be a readable file:

    parser.add_argument('--sqlite-file', type=argparse.FileType('r'))
    

    As a benefit of specifying this type, argparse checks whether the file can be read and displays an error to the user if not.

    Is there a way to obtain the passed filename instead of an instance of io.TextIOWrapper or io.BufferedReader?

    Since the filename appears in the string representation of the parser ('sqlite_file': <_io.TextIOWrapper name='data/export.sqlite' ..., or 'sqlite_file': <_io.BufferedReader name='data/export.sqlite' ...>) it should be possible.

    How to do it?