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

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?

Upvotes: 9

Views: 3579

Answers (1)

larsks
larsks

Reputation: 311476

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)

Upvotes: 13

Related Questions