Search code examples
pythonstringfilenamesargparse

Arg parse: parse file name as string (python)


I would like to parse the name of a file into my script as a string, rather than directly converting the file into an object.

Here is a sample code, test.py:

import argparse
import os.path
def is_valid_file(parser, arg):
      if not os.path.exists(arg):
           parser.error("The file %s does not exist! Use the --help flag for input options." % arg)
      else:
           return open(arg, 'r')

parser = argparse.ArgumentParser(description='test') 
parser.add_argument("-test", dest="testfile", required=True,
                    help="test", type=lambda x: is_valid_file(parser, x))
args = parser.parse_args()    
print args.testfile

testfile is a .txt file containing: 1,2,3,4

In principal would like print args.testfile to return the invoked name of testfile as a string:

$ python test.py -test test.txt
>> "test.txt"

To achieve this I need to prevent argparser from converting test.txt into an object. How can I do this?

Many thanks!


Solution

  • you can modify your function as follows to return the string after having checked it exists:

    def is_valid_file(parser, arg):
          if not os.path.exists(arg):
               parser.error("The file %s does not exist! Use the --help flag for input options." % arg)
          else:
               return arg
    

    There's also a more direct method:

    parser.add_argument("-test", dest="testfile", required=True,
                        help="test", type=file)  # file exists in python 2.x only
    
    parser.add_argument("-test", dest="testfile", required=True,
                        help="test", type=lambda f: open(f))  # python 3.x
    
    args = parser.parse_args()    
    print(args.testfile.name)  # name of the file from the file handle
    

    actually args.testfile is the file handle, opened by argparser (exception if not found). You can read from it directly.