NameError while converting tar.gz to zip
<p>I got the following code from my question on how to convert the tar.gz file to zip file. </p>

<pre><code>import tarfile, zipfile
tarf = tarfile.open(name='sample.tar.gz', mode='r|gz' )
zipf = zipfile.ZipFile.open( name='myzip.zip', mode='a', compress_type=ZIP_DEFLATED )
for m in tarf.getmembers():
    f = tarf.extractfile( m )
    fl = f.read()
    fn = m.name
    zipf.writestr( fn, fl )
tarf.close()
zipf.close()
</code></pre>

<p>but when I run it I get the error.</p>

<p>What should I change in the code to make it work? </p>

<pre><code>NameError: name 'ZIP_DEFLATED' is not defined
</code></pre>

<p><code>ZIP_DEFLATED</code> is a name <a href="https://docs.python.org/2/library/zipfile.html#zipfile.ZIP_DEFLATED" rel="nofollow">defined by the <code>zipfile</code> module</a>; reference it from there:</p>

<pre><code>zipf = zipfile.ZipFile(
    'myzip.zip', mode='a',
    compression=zipfile.ZIP_DEFLATED)
</code></pre>

<p>Note that you don't use the <code>ZipFile.open()</code> method here; you are not opening members in the archive, you are writing <em>to</em> the object.</p>

<p>Also, the correct <a href="https://docs.python.org/2/library/zipfile.html#zipfile.ZipFile" rel="nofollow"><code>ZipFile</code> class signature</a> names the 3rd argument <code>compression</code>. <code>compress_type</code> is only used as an attribute on <code>ZipInfo</code> objects and for the <code>ZipFile.writestr()</code> method. The first argument is not named <code>name</code> either; it's <code>file</code>, but you normally would just pass in the value as a positional argument.</p>

<p>Next, you can't seek in a gzip-compressed tarfile, so you'll have issues accessing members in order if you use <code>tarf.getmembers()</code>. This method has to do a full scan to find all members to build a list, and then you can't go back to read the file data anymore.</p>

<p>Instead, iterate directly over the object, and you'll get member objects in order at a point you can still read the file data too:</p>

<pre><code>for m in tarf:
    f = tarf.extractfile( m )
    fl = f.read()
    fn = m.name
    zipf.writestr( fn, fl )
</code></pre>

python zip tar zipfile tarfile