nori
nori

Reputation: 85

ZipFile archives the folders, too

I want to insert all .ini files into an archive; it does it well but when I open my .zip, there are the path folders to those files included, too.

Here's my code:

from path import Path
import zipfile

def main():

    folderul_cu_demouri = Path('/my/path/bla/bla')
    nume_arhiva = 'demoz.zip'
    arhiva = zipfile.ZipFile(nume_arhiva, 'w')
    for demo in folderul_cu_demouri.files(pattern='*.ini'):

        arhiva.write(demo)

    arhiva.close()  


if __name__ == '__main__':
    main()      

So when I open my zip file, I gotta browse through /my/path/to/files, and only then I can see my .ini files. How can I make it so only the .ini are inserted in the zip file, without the directories?

Thanks.

PS: I'm using path.py to get their extensions.

Upvotes: 0

Views: 47

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140256

if your files are located directly in the archive folder, you could basename your files and pass the name in arcname parameter so the name in the archive is the filename, without the full path:

arhiva.write(demo,arcname=os.path.basename(demo))

else, you could remove the first characters of the full file path so relative paths are preserved:

len_to_strip = len('/my/path/bla/bla')+1

arhiva.write(demo,arcname=demo[:len_to_strip])

Upvotes: 1

Related Questions