Using python to compress a folder is a very useful task. In this article, we will see how to compress and decompress a folder using python.
- Compress a folder using shutil
- Decompress a folder using shutil
- Using zipfile module
- Using python and bash
- Decompress a folder using python and bash
- Conclusion
Compress a folder using shutil
import shutil
shutil.make_archive('folder_name', 'zip', 'folder_path')
Here, folder_name is the name of the compressed folder and folder_path is the path of the folder to be compressed. The make_archive() function takes three arguments. The first argument is the name of the compressed folder. The second argument is the format of the compressed folder. The third argument is the path of the folder to be compressed.
Supported formats are: zip, tar, gztar, bztar, xztar
Decompress a folder using shutil
import shutil
shutil.unpack_archive('folder_name.zip', 'folder_path')
Here, folder_name.zip is the name of the compressed folder and folder_path is the path of the folder to be decompress. The unpack_archive() function takes two arguments. The first argument is the name of the compressed folder. The second argument is the path of the folder to be uncompressed.
Supported formats are: zip, tar, gztar, bztar, xztar
Using zipfile module
import zipfile
with zipfile.ZipFile('folder_name.zip', 'w') as zip:
zip.write('file1')
zip.write('file2')
zip.write('file3')
Here, folder_name.zip is the name of the compressed folder. The ZipFile() function takes two arguments. The first argument is the name of the compressed folder. The second argument is the mode of the compressed folder. The write() function takes one argument. The argument is the file to be compressed.
Using python and bash
import os
os.system('zip -r folder_name.zip folder_path')
Here, folder_name.zip is the name of the compressed folder and folder_path is the path of the folder to be compressed. The os.system() function takes one argument. The argument is the command to be executed. The zip command is used to compress a folder. The -r option is used to compress a folder recursively.
Decompress a folder using python and bash
import os
os.system('unzip folder_name.zip')
Here, folder_name.zip is the name of the compressed folder. The unzip command is used to decompress a folder.
Conclusion
In this article, we have seen how to compress and decompress a folder using python. We have seen how to compress a folder using the shutil module, the zipfile module, and python and bash. We have also seen how to decompress a folder using the shutil module and python and bash.






