简体   繁体   中英

creating zip archive in python

what am I missing in this code (#instead of commented line in code) to have test.py file archived in zip folder ?

#!/usr/bin/python
import zipfile,os
path='/home/user/Desktop'

def zipdir(path, zipf):
  for file in os.walk(path):
    #zipf.write(os.path.join(root,path))




if __name__ == "__main__":

  zipf = zipfile.ZipFile('test.zip', 'w')
  zipdir(path, zipf)
  zipf.close()

The problem is that you're not unpacking all the variables returned by the os.walk() function, so you're telling the program to zip tuples and not paths. You have to make the following changes in the zipdir() function:

def zipdir(path, ziph):
    for root, dirs, files in os.walk(path):
        for file in files:
           ziph.write(os.path.join(root,file))

Check the following answer: How to create a zip archive of a directory

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