read gz file python code example
Example 1: python gzip file
import gzip
f_in = open('/home/joe/file.txt')
f_out = gzip.open('/home/joe/file.txt.gz', 'wb')
f_out.writelines(f_in)
f_out.close()
f_in.close()
Example 2: python Decompress gzip File
import gzip
import shutil
with gzip.open('file.txt.gz', 'rb') as f_in:
with open('file.txt', 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
Example 3: python extract gz file
import tarfile
def extract(tar_file, path):
opened_tar = tarfile.open(tar_file)
if tarfile.is_tarfile(tar_file):
opened_tar.extractall(path)
else:
print("The tar file you entered is not a tar file")
extract('/kaggle/input/gnr-638/train.tar.xz', '/kaggle/working/gnr-638')
extract('/kaggle/input/gnr-638/test_set.tar.xz', '/kaggle/working/gnr-638')
Example 4: python gzip a file
import gzip
import shutil
with open('/home/joe/file.txt', 'rb') as f_in:
with gzip.open('/home/joe/file.txt.gz', 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)