52 lines
1.4 KiB
Python
52 lines
1.4 KiB
Python
"""
|
||
Extracts all .gz files from a given directory and writes the uncompressed
|
||
outputs to an 'out/' subfolder within that directory.
|
||
|
||
Useful for simple, batch decompression of Gzip files via CLI.
|
||
"""
|
||
|
||
import gzip
|
||
from pathlib import Path
|
||
|
||
|
||
def unzip_gzip(file: Path, target: str):
|
||
with gzip.open(file, 'rb') as r:
|
||
with open(target, 'wb') as w:
|
||
return w.write(r.read())
|
||
|
||
|
||
def unzip_gzfiles(dirpath: Path) -> None:
|
||
"""Unzips all .gz files from a given directory into an 'out/' folder."""
|
||
gzfiles = list(dirpath.glob('*.gz'))
|
||
|
||
if not gzfiles:
|
||
print(f'ℹ️ No .gz files found in "{dirpath}"')
|
||
return None
|
||
|
||
# Create a directory to output the files
|
||
Path(f'{dirpath}/out').mkdir(exist_ok=True)
|
||
|
||
for file in gzfiles:
|
||
filename = file.name.removesuffix('.gz')
|
||
|
||
if not file.is_file():
|
||
continue
|
||
|
||
if unzip_gzip(file, f'{dirpath}/out/{filename}'):
|
||
print(f'✅ Unzipped: {file.name}')
|
||
|
||
|
||
if __name__ == '__main__':
|
||
try:
|
||
dirpath = Path(input('📂 Enter the directory containing .gz files: '))
|
||
|
||
if not dirpath.exists() or not dirpath.is_dir():
|
||
print(f'❌ Directory "{dirpath}" not found or is not a folder.')
|
||
exit(1)
|
||
|
||
unzip_gzfiles(dirpath)
|
||
except KeyboardInterrupt:
|
||
print('\n👋 Cancelled by user')
|
||
except Exception as e:
|
||
print(f'💥 Error: {e}')
|