-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzip_extractor.py
More file actions
56 lines (43 loc) · 1.9 KB
/
zip_extractor.py
File metadata and controls
56 lines (43 loc) · 1.9 KB
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
""" zip_extractor.py:
This Python code automatically extracts all ZIP files found in your Downloads folder, creating separate folders for each archive with the same name as the extracted files. """
import os
import zipfile
import logging
# Configure logging for error/progress tracking
logging.basicConfig(filename="zip_extract.log", level=logging.INFO)
def extract_zip(zip_file, output_folder):
"""Extracts the contents of a ZIP file to a specified output folder.
Args:
zip_file (str): Path to the ZIP file.
output_folder (str): Path to the output folder.
Raises:
Exception: If an error occurs during extraction.
"""
try:
with zipfile.ZipFile(zip_file, 'r') as zip_ref:
# Extract all files to the output folder
zip_ref.extractall(output_folder)
logging.info(f"Extracted contents of {zip_file} to {output_folder}")
except Exception as e:
logging.error(f"Error extracting {zip_file}: {e}")
def main():
"""Locates and extracts all ZIP files in the Downloads folder."""
# Get the Downloads folder path
downloads_folder = os.path.expanduser("~/Downloads")
# Find all ZIP files in the Downloads folder
zip_files = [
os.path.join(downloads_folder, file)
for file in os.listdir(downloads_folder)
if file.endswith('.zip')
]
# Extract each ZIP file
for zip_file in zip_files:
# Extract the file name without extension
folder_name = os.path.splitext(os.path.basename(zip_file))[0]
# Create the output folder with the ZIP file name
output_folder = os.path.join(downloads_folder, folder_name)
os.makedirs(output_folder, exist_ok=True) # Create if it doesn't exist
# Extract the ZIP file contents
extract_zip(zip_file, output_folder)
if __name__ == "__main__":
main()