简体   繁体   English

Python - 将文件夹及其内容写入ZipFile

[英]Python - Writing a folder and its contents to a ZipFile

Is it possible to write a folder and its contents to an existing ZipFile? 是否可以将文件夹及其内容写入现有的ZipFile? I've been messing around with this for a while and can only manage to write the folder structure to the archive, anything inside the folder isn't copied. 我已经搞乱了一段时间,只能设法将文件夹结构写入存档,文件夹内的任何内容都不会被复制。 I don't want to point to a specific file, because the idea is that the folder contents can change and the program will just copy the whole folder into the archive no matter what is inside. 我不想指向一个特定的文件,因为这个想法是文件夹内容可以改变,程序只会将整个文件夹复制到存档中,无论内部是什么。

Currently I have, 目前我有,

myzipfile.write('A Folder\\Another Folder\\') 

but I want the contents of 'Another Folder' to be copied as well not just the empty folder 但我想要复制'另一个文件夹'的内容,而不仅仅是空文件夹

Hopefully you understand what I mean. 希望你明白我的意思。

Use os.walk : 使用os.walk

import os
for dirpath,dirs,files in os.walk('A Folder/Another folder'):
  for f in files:
    fn = os.path.join(dirpath, f)
    myzipfile.write(fn)

You have to walk the directory structure adding each file individually. 您必须单独添加每个文件的目录结构。 Use whichever directory walker technique you prefer. 使用您喜欢的任何目录漫游技术。

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

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