How to get the directory of an argparse file in Python?

argparse, path, python

Solution

You can get the name of the file from the `.name` attribute, and then pass this to `os.path.abspath`. For example:

args = parser.parse_args()
path = os.path.abspath(args.file.name)

Problem

I use `argparse` to get a file from the user: ``` import argparse, os parser = argparse.ArgumentParser() parser.add_argument('file', type=file) args = parser.parse_args() ``` Then I want to know the directory where this file is, something like: ``` print(os.path.abspath(os.path.dirname(args.inputfile))) ``` But of course, as `args.inputfile` is a `file` object, this does not work. How to do it?

Original source