Argparse Reopening file.
<p>I'm using the argparse module and I have a log file which is continuously appended to. I want to open args.file, do something with the content, then close it and opening it again after some time. </p>

<p>An example piece of code:</p>

<pre><code>import argparse
import time
parser = argparse.ArgumentParser()
parser.add_argument('file',type=file)
args = parser.parse_args()

for _ in range(3):
    data = args.file.read()
    print data
    time.sleep(3)
</code></pre>

<p>Note that args.file.seek(0) is no solution here. I can close the file with args.file.close() but how to open it again? </p>

<p>I can make the filename-argument just a normal string of the filename but i would like to know a solution keeping the argumenttype as a filename. </p>

<pre><code>parser.add_argument('file',type=file)
</code></pre>

<p>does not mean, <code>the argument is to be a file</code>.  It means</p>

<pre><code>value = file(astring)
args.file = value
</code></pre>

<p>The <code>type</code> parameter is a function that operates on a string.  In Python3 <code>file</code> has been removed; the equivalent would be:</p>

<pre><code>parser.add_argument('file',type=open)
</code></pre>

<p>There is a <code>argparse.FileType</code> class than can be used to open a file with a defined mode; it also recognizes the <code>-</code> value.  This can be useful in small scripts that take an input and output, and do little else.  But generally it is better to open the file yourself, preferably in a <code>with</code> context so ensure it is closed when no longer used.</p>

<pre><code>parser.add_argument('file_name')
args = parser.parse_args()

for _ in range(3):
    with open(args.file_name) as f:
        data = f.read()
    print data
    time.sleep(3)
</code></pre>

<p>What <code>Filetype</code> does do for you is give a 'nice' argparse error message if the file can't be opened.  For example if the name was mistyped in the command line.</p>

python io argparse