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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With