简体   繁体   中英

Append a file to a ZipFile in python

First I created a new zipfile:

import zipfile
zf = zipfile.ZipFile('/data2/new.zip', mode='w')

then I wanted to append a file into the newly created zipfile, say download.py in another folder:

zf.write('/data2/another_folder/download.py')

All seemed fine until I unzip it locally and I found that it did not just append the file, but also append all the folders, data2 and another_folder . I have to open /data2/new/data2/another_folder/ to find download.py .

I want to append and only append the file to zipfile. How can I avoid the aforementioned situation?

Thanks in advance.

The zipfile.write() method takes an optional arcname argument that specifies what the name of the file should be inside the zipfile.

import os
import zipfile


zf.write('/data2/another_folder/download.py', 'download.py')
zf.close()

Here's a function to zip multiple files together:

def zip(list_of_file_paths):
   zf = zipfile.ZipFile("Zipfile.zip", "w", zipfile.ZIP_DEFLATED)
   for path in list_of_file_paths:
       filename = os.path.basename(os.path.normpath(path))
       zf.write(path, filename)
   zf.close()

zip(['path/to/file1', 'path/to/file2', ...]
zf.write('path/to/file.txt', arcname='name_without_path.txt')

should solve that for you, if you want to keep the same name without the path you can also do this:

filepath = 'path/to/file.txt'
zf.write(filepath, arcname=os.path.basename(filepath))

that assumes you did import os of course

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM