W K
W K

Reputation: 1

Python zipfile ExtractAll is not being case sensitive

I am making a Python code to unzip a .zip file and output the content into another. The .zip file contains many files, some with case sensitive file names such as T_N_with_client.docx T_N_with_ lient.docx.

I used ExtractAll to extract everything in the .zip file, however after running the code, the output folder only has one file listed below T_N_with_client.docx However, the content of the file is actually the content of T_N_with_Client.docx.

What is causing this error, and how can I make sure that ensure the program accounts for files that have the same name with different capitalization?

Thanks so much.

import os
import zipfile
from pathlib import Path
from tkinter import Tk
from tkinter.filedialog import askopenfilename

def list_zip_contents(zip_file_path):
    """Lists all files in a zip file without extracting."""
    try:
        with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
            contents = zip_ref.namelist()
            print(f"ZIP file contains {len(contents)} files:")
            for file in contents:
                print(f"{file}")
            return contents
    except (zipfile.BadZipFile, OSError) as e:
        print(f"Error reading the zip file: {e}")
        raise

def extract_zip(zip_file_path, extraction_dir):
    """Extracts a zip file to the specified directory without altering any files."""
    try:
        with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
            zip_ref.extractall(extraction_dir)
        print(f"All files have been extracted to: {extraction_dir}")
    except (zipfile.BadZipFile, OSError) as e:
        print(f"Error extracting the zip file: {e}")
        raise

def main():
    try:
        # Open GUI to select the input zip file
        Tk().withdraw()  # Hide the root window
        zip_file_path = askopenfilename(title="Select the zip file", filetypes=[("Zip files", "*.zip")])
        if not zip_file_path:
            print("No file selected. Exiting.")
            return

        if not os.path.isfile(zip_file_path):
            print("Invalid file path. Please check and try again.")
            return

        # List contents of the ZIP file
        try:
            zip_contents = list_zip_contents(zip_file_path)
        except Exception as e:
            print("Failed to list contents of the zip file. Exiting.")
            return

        # Extract to a directory with the same name as the source zip file (without extension)
        extraction_dir = os.path.splitext(zip_file_path)[0]
        try:
            os.makedirs(extraction_dir, exist_ok=True)
        except OSError as e:
            print(f"Error creating extraction directory: {e}")
            return

        # Extract the ZIP file
        try:
            extract_zip(zip_file_path, extraction_dir)
        except Exception as e:
            print("Failed to extract zip file. Exiting.")
            return

        # Count files in the extracted directory
        extracted_files = list(Path(extraction_dir).rglob("*"))
        print(f"Extracted directory contains {len(extracted_files)} files:")
        for file in extracted_files:
            print(f"  {file}")

    except OSError as e:
        print(f"An OS error occurred: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

if __name__ == "__main__":
    main()

Upvotes: 0

Views: 30

Answers (0)

Related Questions