Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flat files within a zipfile in Python

Tags:

python

I am doing:

z = zipfile.ZipFile('myzip.zip', 'w')
z.write('/some/path/mytxt1.txt')
z.write('/some/other/path/mytxt2.txt')
z.close()

This is preserving the file paths within the zip. I just want my desired files to sit flat in the zip file. How can I do this?

like image 936
Raj Avatar asked Jan 18 '26 18:01

Raj


1 Answers

ZipFile.write() takes the second argument, arcname. Just set it to os.path.basename() of the first argument to remove the path:

def zip_write(zip, filename):
    zip.write(filename, os.path.basename(filename))

z = zipfile.ZipFile('myzip.zip', 'w')
zip_write(z, '/some/path/mytxt1.txt')
zip_write(z, '/some/other/path/mytxt2.txt')
z.close()
like image 65
NPE Avatar answered Jan 20 '26 09:01

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!