How to convert tar.gz file to zip using Python only?
Question: 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
[How can I read tar.gz file using pandas read_csv with gzip compression
option?](http://stackoverflow.com/questions/39263929/how-can-i-read-tar-gz-
file-using-pandas-read-csv-with-gzip-compression-option)


Answer: You would have to use the
[tarfile](https://docs.python.org/3/library/tarfile.html) module, with mode
`'r|gz'` for reading. Then use
[zipfile](https://docs.python.org/3/library/zipfile.html#module-zipfile) for
writing.

    
    
    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()
    

You can use `is_tarfile()` to check for a valid tar file.

Perhaps you could also use
[`shutil`](https://docs.python.org/3/library/shutil.html#archiving-
operations), but I think it cannot work on memory.

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

