1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| import os import zipfile
def zip_file(file_path, zip_file): with zipfile.ZipFile(zip_file, "w", zipfile.ZIP_DEFLATED) as zipf: zipf.write(file_path, arcname=os.path.basename(file_path))
def zip_files(file_path, zip_file): with zipfile.ZipFile(zip_file, "w", zipfile.ZIP_DEFLATED) as zipf: for file in file_path: zipf.write(file, arcname=os.path.basename(file))
def zip_folder(zip_file, folder_path): with zipfile.ZipFile(zip_file, "w", zipfile.ZIP_DEFLATED) as zipf: for root, dirs, files in os.walk(folder_path): for file in files: zipf.write(os.path.join(root, file))
def zip_folders(zip_file, folder_path): with zipfile.ZipFile(zip_file, "w", zipfile.ZIP_DEFLATED) as zipf: for root, dirs, files in os.walk(folder_path): for file in files: zipf.write( os.path.join(root, file), os.path.relpath( os.path.join(root, file), os.path.join(folder_path, "..") ) )
def zip_folders_ext(zip_file, folder_path, extensions): with zipfile.ZipFile(zip_file, "w", zipfile.ZIP_DEFLATED) as zipf: for root, dirs, files in os.walk(folder_path): for file in files: if file.endswith(tuple(extensions)): zipf.write( os.path.join(root, file), os.path.relpath( os.path.join(root, file), os.path.join(folder_path, "..") ) )
def unzip_file(unzip_file, folder_path): with zipfile.ZipFile(unzip_file, "r") as zipf: zipf.extractall(folder_path)
if __name__ == "__main__": zip_file(r"./file/json_file.json", r"zip/zip_file.zip") zip_files([ r"./file/json_file.json", r"./file/sqlite3_file.db", r"./file/csv_file.csv" ], r"zip/zip_files.zip") zip_folder( r"zip/zip_folder.zip", r"./file" ) zip_folders(r"zip/zip_folders.zip", r"./file") zip_folders_ext(r"zip/zip_folders_ext.zip", r"./file", ".csv") unzip_file(r"zip/zip_file.zip", "./zip") unzip_file(r"zip/zip_folders.zip", "./zip")
|