How to get the argparse file directory in Python?

I use argparse to get the 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 in which this file is, something like:

 print(os.path.abspath(os.path.dirname(args.inputfile))) 

But of course, since args.inputfile is a file object, this does not work. How to do it?

+8
python path argparse
source share
1 answer

You can get the file name from the .name attribute and then pass it to os.path.abspath . For example:

 args = parser.parse_args() path = os.path.abspath(args.file.name) 
+12
source share

All Articles