简体   繁体   English

在python中创建zip存档

[英]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 ? 在此代码中我缺少什么(用#代替代码中的注释行)将test.py文件存档在zip文件夹中?

#!/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. 问题是您没有解压缩os.walk()函数返回的所有变量,所以您要告诉程序压缩元组而不是路径。 You have to make the following changes in the zipdir() function: 您必须在zipdir()函数中进行以下更改:

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 检查以下答案: 如何创建目录的zip存档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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