'Zipfile with no parent folder

I am able to compress files into a single zip file, however when I open the zip file the contents always include a "parent folder" which has the same exact name as the zip file itslef.

I'm simply trying to create a zip file that contains no folders at all.

Current: abc.zip > abc (folder) > files

Looking for: abc.zip > files

def create_zip(file_name, file_dir):
    """
    Function to create zip archive
    """
    os.chdir(file_dir)
    zipfiles_list = ['csv', 'txt']
    file_name_part = file_name
    zip_name = '{0}.zip'.format(file_name_part)
    with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) as 
    zip_archive:
        for file_extension in zipfile_list:
            full_file_path = '{0}.{1}'.format(file_name_part, file_extension)
            zip_archive.write(full_file_path, basename(full_file_path))

Is this possible? I've seen that if I rename the zip file after it's created, it will still extract contents into a folder that matches the zip file name.

Original zip extracts to abc folder

Renamed same exact zip and contents extract to folder with new name



Solution 1:[1]

In your code you have a mistake in a word 'zipfiles': for file_extension in zipfile_list: (without 's' in the end).

It have to be for file_extension in zipfiles_list:.

Than I run your code in Win7x86 - it is OK, no inner folder (python 3.6.6).

Tried it on Win 10x64 - same.

Xubuntu 18.04 x64 - same, without folder.

Here is my script:

from os.path import basename 
from os import path
import os
import zipfile

# current directory
script_dir = path.dirname(path.abspath(__file__))

def create_zip(file_name, file_dir):
    """
    Function to create zip archive
    """
    os.chdir(file_dir)
    zipfiles_list = ['csv', 'txt']
    file_name_part = file_name
    zip_name = '{0}.zip'.format(file_name_part)
    with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) as zip_archive:
        for file_extension in zipfiles_list:
            full_file_path = '{0}.{1}'.format(file_name_part, file_extension)
            zip_archive.write(full_file_path, basename(full_file_path))

create_zip("first", script_dir)

In a directory with script there two files: first.txt and first.csv. After runing this scrip I do have zip file first.zip with two files inside: first.txt and first.csv.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1