How to convert tar.gz file to zip using Python only?
<p>Does anybody has any code for converting tar.gz file into zip using only Python code? I have been facing many issues with tar.gz as mentioned in the <a href="http://stackoverflow.com/questions/39263929/how-can-i-read-tar-gz-file-using-pandas-read-csv-with-gzip-compression-option">How can I read tar.gz file using pandas read_csv with gzip compression option?</a></p>

<p>You would have to use the <a href="https://docs.python.org/3/library/tarfile.html" rel="nofollow">tarfile</a> module, with mode <code>'r|gz'</code> for reading.
Then use <a href="https://docs.python.org/3/library/zipfile.html#module-zipfile" rel="nofollow">zipfile</a> for writing.</p>

<pre><code>import tarfile, zipfile
tarf = tarfile.open( name='mytar.tar.gz', mode='r|gz' )
zipf = 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 )
    # or zipf.writestr( fn, f ) ?
tarf.close()
zipf.close()
</code></pre>

<p>You can use <code>is_tarfile()</code> to check for a valid tar file.</p>

<p>Perhaps you could also use <a href="https://docs.python.org/3/library/shutil.html#archiving-operations" rel="nofollow"><code>shutil</code></a>, but I think it cannot work on memory.</p>

<p>PS: I do not have python in this PC, so there may be a few things to tune.</p>

python zip tar