#!/usr/bin/env pythonimport osimport zipfile
def addDirToZip(zipHandle, path, basePath=""):"""Adding directory given by \a path to opened zip file \a zipHandle
@param basePath path that will be removed from \a path when adding to archive
Examples:# add whole "dir" to "test.zip" (when you open "test.zip" you will see only "dir")zipHandle = zipfile.ZipFile('test.zip', 'w')addDirToZip(zipHandle, 'dir')zipHandle.close()
# add contents of "dir" to "test.zip" (when you open "test.zip" you will see only it's contents)zipHandle = zipfile.ZipFile('test.zip', 'w')addDirToZip(zipHandle, 'dir', 'dir')zipHandle.close()
# add contents of "dir/subdir" to "test.zip" (when you open "test.zip" you will see only contents of "subdir")zipHandle = zipfile.ZipFile('test.zip', 'w')addDirToZip(zipHandle, 'dir/subdir', 'dir/subdir')zipHandle.close()
# add whole "dir/subdir" to "test.zip" (when you open "test.zip" you will see only "subdir")zipHandle = zipfile.ZipFile('test.zip', 'w')addDirToZip(zipHandle, 'dir/subdir', 'dir')zipHandle.close()
# add whole "dir/subdir" with full path to "test.zip" (when you open "test.zip" you will see only "dir" and inside it only "subdir")zipHandle = zipfile.ZipFile('test.zip', 'w')addDirToZip(zipHandle, 'dir/subdir')zipHandle.close()
# add whole "dir" and "otherDir" (with full path) to "test.zip" (when you open "test.zip" you will see only "dir" and "otherDir")zipHandle = zipfile.ZipFile('test.zip', 'w')addDirToZip(zipHandle, 'dir')addDirToZip(zipHandle, 'otherDir')zipHandle.close()"""basePath = basePath.rstrip("\\/") + ""basePath = basePath.rstrip("\\/")for root, dirs, files in os.walk(path):# add dir itself (needed for empty dirszipHandle.write(os.path.join(root, "."))# add filesfor file in files:filePath = os.path.join(root, file)inZipPath = filePath.replace(basePath, "", 1).lstrip("\\/")#print filePath + " , " + inZipPathzipHandle.write(filePath, inZipPath)
import osimport zipfile
def zipdir(path, ziph):# Iterate all the directories and filesfor root, dirs, files in os.walk(path):# Create a prefix variable with the folder structure inside the path folder.# So if a file is at the path directory will be at the root directory of the zip file# so the prefix will be empty. If the file belongs to a containing folder of path folder# then the prefix will be that folder.if root.replace(path,'') == '':prefix = ''else:# Keep the folder structure after the path folder, append a '/' at the end# and remome the first character, if it is a '/' in order to have a path like# folder1/folder2/file.txtprefix = root.replace(path, '') + '/'if (prefix[0] == '/'):prefix = prefix[1:]for filename in files:actual_file_path = root + '/' + filenamezipped_file_path = prefix + filenamezipf.write( actual_file_path, zipped_file_path)
zipf = zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED)zipdir('/tmp/justtest/', zipf)zipf.close()
from shutil import make_archivemake_archive('zipfile_name','zip', # the archive format - or tar, bztar, gztarroot_dir=None, # root for archive - current working dir if Nonebase_dir=None) # start archiving from here - cwd if None too
def zip_dir(filename: str, dir_to_zip: pathlib.Path):with zipfile.ZipFile(filename, 'w', zipfile.ZIP_DEFLATED) as zipf:# Use glob instead of iterdir(), to cover all subdirectories.for directory in dir_to_zip.glob('**'):for file in directory.iterdir():if not file.is_file():continue# Strip the first component, so we don't create an uneeded subdirectory# containing everything.zip_path = pathlib.Path(*file.parts[1:])# Use a string, since zipfile doesn't support pathlib directly.zipf.write(str(file), str(zip_path))
# import required python modules# You have to install zipfile package using pip install
import os,zipfile
# Change the directory where you want your new zip file to be
os.chdir('Type your destination')
# Create a new zipfile ( I called it myfile )
zf = zipfile.ZipFile('myfile.zip','w')
# os.walk gives a directory tree. Access the files using a for loop
for dirnames,folders,files in os.walk('Type your directory'):zf.write('Type your Directory')for file in files:zf.write(os.path.join('Type your directory',file))
cwd = os.getcwd()files = [os.path.join(cwd, f) for f in ['dir4', 'root.txt']]
with zipfile.ZipFile("selective.zip", "w" ) as myzip:for f in files:zipall(myzip, f)
或者只需在脚本调用目录中listdir并从那里添加所有内容:
with zipfile.ZipFile("listdir.zip", "w" ) as myzip:for f in os.listdir():if f == "listdir.zip":# Creating a listdir.zip in the same directory# will include listdir.zip inside itself, beware of thiscontinuezipall(myzip, f)
def CREATEZIPFILE(zipname, path):#function to create a zip file#Parameters: zipname - name of the zip file; path - name of folder/file to be put in zip file
zipf = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)zipf.setpassword(b"password") #if you want to set password to zipfile
#checks if the path is file or directoryif os.path.isdir(path):for files in os.listdir(path):zipf.write(os.path.join(path, files), files)
elif os.path.isfile(path):zipf.write(os.path.join(path), path)zipf.close()
$ cat zip_cap_dirs.py""" Zip 'cap_*' directories. """import osimport zipfile as zf
for root, dirs, files in sorted(os.walk('.')):if 'cap_' in root:print(f"Compressing: {root}")# Defining .zip name, according to Capítulo.cap_dir_zip = '{}.zip'.format(root)# Opening zipfile context for current root dir.with zf.ZipFile(cap_dir_zip, 'w', zf.ZIP_DEFLATED) as new_zip:# Iterating over os.walk list of files for the current root dir.for f in files:# Defining relative path to files from current root dir.f_path = os.path.join(root, f)# Writing the file on the .zip file of the contextnew_zip.write(f_path)
def zip_dir(dir: Union[Path, str], filename: Union[Path, str]):"""Zip the provided directory without navigating to that directory using `pathlib` module"""
# Convert to Path objectdir = Path(dir)
with zipfile.ZipFile(filename, "w", zipfile.ZIP_DEFLATED) as zip_file:for entry in dir.rglob("*"):zip_file.write(entry, entry.relative_to(dir))