Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 652
Stéphane Péchard Avatar asked May 07 '12 16:05

Stéphane Péchard


1 Answers

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)
like image 156
larsks Avatar answered Oct 14 '22 11:10

larsks