Hello Techies π,
It's been so long we had spoken. Now , here I am with another interesting Blog. So Why late? Let's get Started.
We all know how to compress a file or group of files into a zip or tarfile. Why don't we try doing it with Python?
Yes, We can. In this Blog, We will be going to know how to compress files into a tarfile with python.
Prerequisites:
- tarfile
- tqdm
Well, I hope you all have Python installed in your system. Let me explain you how we are going to use the above modules.
tqdm is a library which is basically used to display the progress bars. We just use here to know the Progress of our process when we are trying to run the Program.
tarfile is used to perform various operations with the tarfiles. We can add, append, or create tarfiles.
Installation: We can install the libraries using the below commands.
pip install tqdm
pip install tarfile
Okay, Now time to codeπ
Step 1:First lets import the required libraries.
import tarfile
from tqdm import tqdm
Step 2:Now, we are gonna create a variable which takes in a file name
and the mode
to create a new tar file.
tar = tarfile.open("tar_file.tar.gz", mode="w:gz")
Step 3: In this step, We will Create a ProgressBar
to track the progress of our compression process.
member = "files to compress/folder path"
progress = tqdm(member)
In the above code, member is the variable which stores the path of the files to be compressed. You can also pass in a list.
Step 4: Now, We add the files into the tar variable to compress using the following code.
tar.add(member)
The add()
method takes in the member
variable.
Step 5: It's time to set the Progress Bar into action. The following code does this.
progress.set_description(f"Compressing {member}")
tar.close()
set_description
method of progress variable is just used to display the description when the progress bar is running. The output can be as follows.
Next we need to set tar to close using tar.close()
.
You can find the complete code in my GitHub repository.
Please leave a β if you find it interesting.
Well Done ! All Set. Now run your Program to see the result.
Thanks for reading. Please Drop in your Comments/Suggestions. Happy Learning :)