How to compress text files using Python

Опубликовано: 27 Май 2022
на канале: buckmasterinstitute
1,356
8

Created and recorded by Jeffano John, May 2022.

Script

Sometimes, a file can take up large amounts of space on your PC making it difficult to send it over to other people and it could be vulnerable to viruses, especially if it is sent over wireless networks. In this tutorial, I will be showing you how to compress a text file and a folder using Python.

First, we need to install these two packages:
The os package
zipfile
From zipfile, we need to import zipfile.

Then, we assign the file name to a variable. In this case, the Python script is located within the same folder as the textfile. Then we type:
f = ZipFile('textcomp.zip', 'w')
We assign f to zip the file and name it ‘textcomp.zip’. The w stands for “write’ to write the file.

f.write(txtfile)

This compresses the file.

f.close()

This closes the opened file.

Now to compress a folder, we do the same as before by assigning a variable to the name of the folder. Show the folder and the files within.
folder = 'randomfolder'

Then assign fol to compress the folder.
fol = ZipFile('foldercomp.zip', 'w')

Next, we create a for loop to zip the whole folder.
for root, dirs, files in os.walk(folder):
for file in files:
This basically lists all the files in the folder and we can ask it to print the file names and the path however we want to compress it. So to compress it, we ask:
fol.write(os.path.join(root, file))

Then we close the opened folder
fol.close()

This is how we can compress files and folders using python.