To convert a file to tar.gz in Python, use the gzip.open() function. The gzip.open() function opens a gzip-compressed file in binary or text mode, returning a file object. The gzip module provides the open(), compress(), and decompress() convenience functions.
Program to convert file to .gz
import gzip file = open("/Users/krunallathiya/Desktop/Code/R/sample.txt") zipped = gzip.open("/Users/krunallathiya/Desktop/Code/R/sample.tar.gz", "wb") zipped.writelines(file) zipped.close() file.close()
It will create a sample.tar.gz file in your current working directory.
In this program, we imported a package called the gzip, which can be used for creating a zip file. Then, we use gzip package for converting a file into a zip file.
The next line opened the text file we wanted to zip, so we opened the sample.txt file present in the system. Next, we used the package to open the file as a zip file.
We create a zip file in write binary mode. Then, in the next line, we write the contents from the text file into the file created inside the zip folder. This is equivalent to the write operation. We then closed the two opened files.
We use the close() function to close the file. We can replace the close() function with the open statement. With open statement automatically closes the file once the intended block is executed.
import gzip with open("/Users/krunallathiya/Desktop/Code/R/sample.txt") as file: with gzip.open("/Users/krunallathiya/Desktop/Code/R/tar.gz", "wb") as zipped: zipped.writelines(file)
In this program, we used with open() function to open the files.
How to convert a folder to tar.gz
To convert a folder to tar.gz in Python, use the with tarfile.open() function. The tarfile is a Python module used to read and write tar archives.
import os import tarfile def Converter(path, tar): with tarfile.open(tar, "w:gz") as t: for root, dirs, files in os.walk(path): for file in files: t.add(os.path.join(root, file)) Converter("/Users/krunallathiya/Desktop/Code/R/", "sample.tar.gz")
It will create a sample.tar.gz file inside your current working directory.
In this program, we imported the os and tarfile modules. The os package is used for locating the file in the local system. The os module is used primarily for walking into the systems memory locations.
The tarfile package is used for creating a zip file. It converts the folder into a tar file. The tarfile package compresses the folder size and stores it in the zip file. We called a user-defined function called converter(). We pass the folder we want to compress, and the next one is the tar folder name to which we want to save.
We opened the tar folder in write mode using a tarfile.open() function inside the function. We then store all the files present in the folder in the tar folder. Finally, we add all the files and folders into the tar.gz file.
To convert a file to a tar.gz file, use the gzip.open() function.
To convert a folder to a tar.gz file, use the tarfile.open() function.
That’s it for this tutorial.