[Python] Gzip files extraction

Discussão em 'Python' iniciado por Stack, Abril 14, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to extract .pkl files from the .zip files that are actually gzips. I have tried gunzip but it only works with .gzip extension.

    I have tried the following but it gives me all the data (pkl,ekl & crc) in one pkl file.

    def extract_gzip_file_and_create_folder(event):
    source_path = event['source_path']
    target_path = event['target_path']
    gzip_files = [file for file in os.listdir(source_path) if file.endswith('.zip')]

    for gzip_file in gzip_files:
    source_file = os.path.join(source_path, gzip_file)
    # Create a folder for each file in the target path
    folder_name = os.path.splitext(gzip_file)[0] # Remove '.zip'
    folder_path = os.path.join(target_path, folder_name)
    os.makedirs(folder_path, exist_ok=True) # Create the folder if it doesn't exist

    try:
    with gzip.open(source_file, 'rb') as f_in:
    for file_name in ['pkl', 'ekl']:
    target_file = os.path.join(folder_path, folder_name + '.' + file_name)
    with open(target_file, 'wb') as f_out:
    shutil.copyfileobj(f_in, f_out)
    print(f"Extracted: {gzip_file} to {target_file}")
    except Exception as e:
    print(f"An error occurred while extracting {gzip_file}: {e}")

    Continue reading...

Compartilhe esta Página