What is the best way to "force" users to use a certain file extension with argparse?
<p>I have a script which users include the pathnames for the input and output files. </p>

<pre><code>import argparse

parser = argparse.ArgumentParser()
parser.add_argument("i", help = "input path")
parser.add_argument("o", help = "output path")
args = parser.parse_args()
file_input = args.input
file_output = args.output
</code></pre>

<p>Now, I want to make sure that users create an output file that is a text file, with extension <code>.txt</code>. </p>

<p>(1) I could possible through an error, telling users that they <em>must</em> use a txt extension. </p>

<p>(2) I could check whether a <code>.txt</code> extension has been used. If not, I would simply add it. </p>

<p>The first is relatively easy:</p>

<pre><code>import argparse

parser = argparse.ArgumentParser()
parser.add_argument("i", help = "input path")
parser.add_argument("o", help = "output path")
args = parser.parse_args()
file_input = args.input
file_output = args.output
if file_output.endswith("txt") != True:
    raise argparse.ArgumentTypeError('File must end in extension .txt!')
</code></pre>

<p>How would one accomplish the latter? </p>

<p>You could define a <code>type</code> function that adds the required extension, e.g.</p>

<pre><code>def txtname(astr):
    if not astr.endswith('.txt'):
        astr += '.txt'
    return astr

In [724]: parser=argparse.ArgumentParser()
In [725]: parser.add_argument('-i',type=txtname);
In [726]: parser.add_argument('-o',type=txtname);
In [728]: parser.parse_args(['-i','inname','-o','oname.txt'])
Out[728]: Namespace(i='inname.txt', o='oname.txt')
</code></pre>

<p>That function could also raise a ValueError if you don't like certain extensions or forms of filename.</p>

python python-3.x argparse file-extension