I need the file path and os.path.dirname does not give me the complete path (it does not include the file itself - e.g. home/a/b instead of home/a/b/filename). Also I need the file name so that I can print it later. Since the argument the user inputs IS the filename, I need a way to store the input into a list.
import sys
import argparse
import inspect, os
import os.path
file_list = []
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('file', type=argparse.FileType('r'), nargs='*')
args = parser.parse_args()
for f in args.file:
with f:
data = f.read()
print data
x = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
print x
file_list.append(x+#I need the filename here)
You can use os.path.abspath(f.name) to get the absolute filepath that was used to open the file f.
However, if you also want the filepath, it may be cleaner to just not convert the type to a fileobject, and do this yourself later, instead of trying to reverse-engineer where the open file came from. This way you will already have the list of filepaths, e.g.:
file_list = []
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='*')
args = parser.parse_args()
for filepath in args.file:
x = os.path.abspath(filepath)
with open(filepath, 'r') as f:
data = f.read()
print data
file_list.append(x)
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