Using python to zip files

Publicado el: 02 marzo 2020
en el canal de: linuxhint
19,024
129

In this video, we have explained to you that how we can create zip files using python. First of all we have written a program in python to make zip files from existing files, after that we have written a program in python to add directories and multiple paths to our zip file. Pycharm IDE is used in this video.
-------------------------------------------------------------------------------------------------
Code for creating zip file from existing files:
import zipfile
zip_file = zipfile.ZipFile('temp.zip','w')
zip_file.write('temp.txt', compress_type=zipfile.ZIP_DEFLATED)
zip_file.close()
---------------------------------------------------------------------------------------------------
Code for adding directories and multiple paths to our zip file
importing required modules
from zipfile import ZipFile
import os

def get_all_file_paths(directory):

initializing empty file paths list
file_paths = []

crawling through directory and subdirectories
for root, directories, files in os.walk(directory):
for filename in files:
join the two strings in order to form the full filepath.
filepath = os.path.join(root, filename)
file_paths.append(filepath)

returning all file paths
return file_paths

def main():
path to folder which needs to be zipped
directory = './myfolder'

calling function to get all file paths in the directory
file_paths = get_all_file_paths(directory)

printing the list of all files to be zipped
print('Following files will be zipped in this program:')
for file_name in file_paths:
print(file_name)

writing files to a zipfile
with ZipFile('myzipfile.zip','w') as zip:
writing each file one by one
for file in file_paths:
zip.write(file)

print('All files zipped successfully!')


if _name_ == "__main__":
main()



#linuxhint #python


En esta página del sitio puede ver el video en línea Using python to zip files de Duración hora minuto segunda en buena calidad , que subió el usuario linuxhint 02 marzo 2020, comparta el enlace con amigos y conocidos, en youtube este video ya ha sido visto 19,024 veces y le gustó 129 a los espectadores. Disfruta viendo!