Search code examples
pythonzipos.walkpython-zipfile

ZipFile puts all parent directories inside newly created zip file


I want to create a zipfile from a select few individual files. Here is my code so far:

from zipfile import ZipFile
from os import walk

name = 'Mia'

allFiles = next(walk("C:\\Users\\jack_l\\Documents\\Image-Line\\FL Studio\\Projects\\finished\\UPLOAD"), (None, None, []))[2]

allStemFiles = []

for counter in range(len(allFiles)):
    if str('STEMS - '+name) in allFiles[counter]:
        allStemFiles.append(allFiles[counter])

myZipFile = ZipFile(r'C:\Users\jack_l\Documents\Image-Line\FL Studio\Projects\finished\UPLOAD\beatTitle.zip', 'w')

for counter in range(len(allStemFiles)):
    myZipFile.write('C:\\Users\\jack_l\\Documents\\Image-Line\\FL Studio\\Projects\\finished\\UPLOAD\\'+allStemFiles[counter])

myZipFile.close()

My issue is that it does create a zipfile in the correct directory (C:..../UPLOAD), but the zipfile it creates contains 8 layers of folders over the files. Like the zip file contains a folder called Users, which contains a folder called jack_l, and so on until a folder called UPLOAD contains my files.

I tried to fix this by writing:

myZipFile.write(allStemFiles[counter])

instead of:

myZipFile.write('C:\\Users\\jack_l\\Documents\\Image-Line\\FL Studio\\Projects\\finished\\UPLOAD\\'+allStemFiles[counter])

but then I get the following error: enter image description here

Any help would be greatly appreciated. Just to re-iterate; I want a zipfile only containing the files (no folders whatsoever). Thank you.


Solution

  • You can change the working directory to the base directory of files to be archived first so that all paths become relative to the base directory:

    from zipfile import ZipFile
    import os
    
    name = 'Mia'
    
    os.chdir("C:\\Users\\jack_l\\Documents\\Image-Line\\FL Studio\\Projects\\finished\\UPLOAD")
    
    allFiles = next(os.walk("."), (None, None, []))[2]
    
    allStemFiles = []
    
    for counter in range(len(allFiles)):
        if str('STEMS - '+name) in allFiles[counter]:
            allStemFiles.append(allFiles[counter])
    
    myZipFile = ZipFile('beatTitle.zip', 'w')
    
    for counter in range(len(allStemFiles)):
        myZipFile.write(allStemFiles[counter])
    
    myZipFile.close()