Using argparse, how can I put user input into a list?

I want the path to the file, os.path.dirname

not giving me the full path (it doesn't include the file itself - for example home/a/b

instead of home/a/b/filename

). Also I need the name of the file so that I can print it later. Since the argument is user enters a filename, I need a way to store the input in 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)

      

+3


source to share


3 answers


You can use os.path.abspath(f.name)

to get the absolute path to the file that was used to open the file f

.

However, if you also want a file path, it might be cleaner to just not convert that type to file file, and do it yourself later, instead of trying to reverse engineer where the open file came from. Thus, you will already have a list of file paths, for example:



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)

      

+4


source


You can get the full path of the file handler using os.path.abspath(fl.name)

, so this should work:

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
            full_path = os.path.abspath(f)
            file_list.append(full_path)

      



Further refer to os.path.basename

, which only returns the pathname component.

+1


source


What about

os.path.realpath(f.name)

      

This concatenates the current version with the filename recorded in f.name

.

If this is not efficient enough, you can accept the filename from the user and open the file yourself. FileType

is not essential. It's just a convenience type, most useful in scripts that take input and output files and do something simple with them. In other words, scripts that combine common functionality bash

.

+1


source







All Articles