简体   繁体   中英

How to add multiple files into a single zip folder

Actually i am writting a script which writes two files into a desktop, let it be as "a.txt" and "b.txt"....... so after writing into a desktop i have to read this files and zip into a folder....

can anyone help on this....i know how to zip a folder but dono how to add two files in to a zip

Reading from folder i know its like this

def zipdir(basedir, archivename):
    assert os.path.isdir(basedir)
    with closing(ZipFile(archivename, "w", ZIP_DEFLATED)) as z:
        for root, dirs, files in os.walk(basedir):
            for fn in files:
                absfn = os.path.join(root, fn)
                zfn = absfn[len(basedir)+len(os.sep):]
                z.write(absfn, zfn)

if __name__ == '__main__':
    import sys
    basedir = sys.argv[1]
    archivename = sys.argv[2]
    zipdir(basedir, archivename)

The code which now i using is

import zipfile
zip = zipfile.ZipFile('Python.zip', 'a')
zip.write('fields.txt')
zip.write('grp.txt')
zip.close()

This is creating file of those two plus some extra folder which contains all files.......

you need to open the zip file with "a" -append parameter. Then you can use the write parameter without overwriting the file.

source: 12.4.1

EDIT:

zip.write('file.pdf','/folder/file.pdf')

The easiest wayh is to use shutil library. put all the files you want to zip in a single directoty(folder)

import shutil
shutil.make_archive(output_filename_dont_add_.zip, 'zip', directory_to_download)

Remember if you work with ipython you can use relative address for directory_to_download

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