Arg parse: parse file name as string (python)
<p>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.</p>

<p>Here is a sample code, <code>test.py</code>:</p>

<pre><code>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
</code></pre>

<p><code>testfile</code> is a <code>.txt</code> file containing: <code>1,2,3,4</code></p>

<p>In principal would like <code>print args.testfile</code> to return the invoked name of <code>testfile</code> as a string:</p>

<pre><code>$ python test.py -test test.txt
&gt;&gt; "test.txt"
</code></pre>

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

<p>Many thanks!</p>

<p>you can modify your function as follows to return the string after having checked it exists:</p>

<pre><code>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
</code></pre>

<p>There's also a more direct method:</p>

<pre><code>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
</code></pre>

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

python string filenames argparse