xxxxxxxxxx
#!/usr/bin/env python
import os
import zipfile
def zipdir(path, ziph):
# ziph is zipfile handle
for root, dirs, files in os.walk(path):
for file in files:
ziph.write(os.path.join(root, file))
if __name__ == '__main__':
zipf = zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED)
zipdir('tmp/', zipf)
zipf.close()
xxxxxxxxxx
import shutil
shutil.make_archive(output_filename, 'zip', dir_name)
xxxxxxxxxx
import os
import zipfile
def zip_directory(folder_path, zip_path):
with zipfile.ZipFile(zip_path, mode='w') as zipf:
len_dir_path = len(folder_path)
for root, _, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
zipf.write(file_path, file_path[len_dir_path:])
zip_directory('C:/FolderToZip', 'C:/Folder.zip')
xxxxxxxxxx
# 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 = './python_files'
# 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:')
for file_name in file_paths:
print(file_name)
# writing files to a zipfile
with ZipFile('my_python_files.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()