Last active
November 7, 2023 01:36
-
-
Save don1138/a69a92d97641abc92909f38014184d19 to your computer and use it in GitHub Desktop.
Compress file or folders using Python's zipfile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Zip File v1.2.0 | |
# Usage: python zip_file.py | |
import os | |
import shlex | |
import zipfile | |
# Ask the user for the file or directory path to compress | |
source_path_input = input("Enter the file or directory path to compress: ").strip() | |
# Use shlex to sanitize the path | |
source_path_components = shlex.split(source_path_input) | |
source_path = ' '.join(source_path_components) | |
# Check if the path exists | |
if not os.path.exists(source_path): | |
print(f"Path '{source_path}' does not exist.") | |
else: | |
# Determine the name for the zip file | |
if os.path.isdir(source_path): | |
base_zip_filename = os.path.basename(source_path) + '.zip' | |
else: | |
base_zip_filename = os.path.basename(source_path) + '.zip' | |
zip_filename = os.path.join(os.path.dirname(source_path), base_zip_filename) | |
counter = 1 | |
# Check if the zip file already exists and find a non-existing filename | |
while os.path.exists(zip_filename): | |
zip_filename = os.path.join( | |
os.path.dirname(source_path), | |
f"{os.path.splitext(base_zip_filename)[0]}_{counter}.zip" | |
) | |
counter += 1 | |
# Open the zip file for writing | |
with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf: | |
if os.path.isdir(source_path): | |
for root, dirs, files in os.walk(source_path): | |
for file in files: | |
file_path = os.path.join(root, file) | |
rel_path = os.path.relpath(file_path, source_path) | |
zipf.write(file_path, rel_path) | |
else: | |
zipf.write(source_path, os.path.basename(source_path)) | |
print(f'Successfully compressed to {zip_filename}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment