pythonzippython-zipfile

Function to unzip .zip file in Python not working


I have this function which is supposed to take a .zip file, unzip it, and put the files in the same directory where the .zip file was originally located:

def unzip_file(file_path):
    print(f"Unzipping file: {file_path}")
    if os.path.exists(file_path):
        if file_path[-4:] == ".zip":
            with zipfile.ZipFile(file_path, 'r') as zip_ref:
                try:
                    for file_name in zip_ref.namelist():
                        print(f"Found in zip: {file_name}")
                    print(os.path.dirname(file_path))
                    zip_ref.extractall(path=os.path.dirname(file_path))
                except Exception as e:
                    print(f"Error unzipping file: {e}")
            os.remove(file_path)
        else:
            print(f"File is not a zip file: {file_path}")
    else:
        print(f"File does not exist: {file_path}")

However, I'm receiving an error and I'm not sure why.

Let's say my zip file is called zip_file.zip, and it is located at C:\example_folder\zip_file.zip.

Let's also say it has three text files in it: a.txt, b.txt, c.txt, and no folders in it.

My error looks like:

Unzipping file: C:\example_folder\zip_file.zip
Found in zip: a.txt
Found in zip: b.txt
Found in zip: c.txt
C:\example_folder
Error unzipping file: [Errno 2]: No such file or directory- 'C:\\example_folder\\zip_file.zip\\a.txt'

Does anyone know why extractall() is not working? Thanks in advance for helping me!

EDIT: fixed the problem- the file path was too long, this is just for anyone else who had a similar issue (make sure your file path isn't over 256 characters)


Solution

  • I think I found an answer to my own question:

    example_folder isn't the actual name of my folder - I just didn't want to reveal personal information that came with the folder (as my real name was contained in one of the paths), and I didn't think the length of the path was an issue so I wanted to simplify the question.

    In Windows, paths that are over 256 characters long can cause issues, and it just so happened my path was approaching that limit.

    To fix this, use "\\?\" and put at the front of the file path- which extends the limit to 32,767 characters