使用python将文件夹添加到zip文件中 [英] Adding folders to a zip file using python
问题描述
我想创建一个zip文件。将文件夹添加到zip文件中,然后将一堆文件添加到该文件夹中。
I want to create a zip file. Add a folder to the zip file and then add a bunch of files to that folder.
因此,我想最终得到一个压缩文件,其中只有一个文件夹,其中包含文件
So I want to end up with a zip file with a single folder with files in.
我不知道在zip文件或其他内容中包含文件夹是不是一种不好的做法,但google却使我对此一无所知。
I dont know if its bad practice to have folders in zip files or something but google gives me nothing on the subject.
我从这里开始:
def addFolderToZip(myZipFile,folder):
folder = folder.encode('ascii') #convert path to ascii for ZipFile Method
for file in glob.glob(folder+"/*"):
if os.path.isfile(file):
print file
myZipFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED)
elif os.path.isdir(file):
addFolderToZip(myZipFile,file)
def createZipFile(filename,files,folders):
curTime=strftime("__%Y_%m_%d", time.localtime())
filename=filename+curTime;
print filename
zipFilename=utils.getFileName("files", filename+".zip")
myZipFile = zipfile.ZipFile( zipFilename, "w" ) # Open the zip file for writing
for file in files:
file = file.encode('ascii') #convert path to ascii for ZipFile Method
if os.path.isfile(file):
(filepath, filename) = os.path.split(file)
myZipFile.write( file, filename, zipfile.ZIP_DEFLATED )
for folder in folders:
addFolderToZip(myZipFile,folder)
myZipFile.close()
return (1,zipFilename)
(success,filename)=createZipFile(planName,files,folders);
来自: http://mail.python.org/pipermail/python-list/2006-August/396166.html
将删除所有文件夹,并将目标文件夹(及其子文件夹)中的所有文件放入单个zip文件中。我无法获取它来添加整个文件夹。
Which gets rid of all folders and puts all files in the target folder (and its subfolders) into a single zip file. I couldnt get it to add an entire folder.
如果我将路径输入myZipFile.write中的文件夹,则会得到
If I feed the path to a folder in myZipFile.write, I get
IOError:[Errno 13]权限被拒绝:'..\packed\bin'
IOError: [Errno 13] Permission denied: '..\packed\bin'
非常欢迎任何帮助。
相关问题:如何使用python(2.5版)压缩文件夹的内容?
推荐答案
好吧,在我理解了您想要的内容之后,它就像使用 zipfile.write $的第二个参数一样简单。 c $ c>,您可以在其中使用所需的任何内容:
Ok, after i understood what you want, it is as simple as using the second argument of zipfile.write
, where you can use whatever you want:
import zipfile
myZipFile = zipfile.ZipFile("zip.zip", "w" )
myZipFile.write("test.py", "dir\\test.py", zipfile.ZIP_DEFLATED )
创建一个zipfile,将 test.py
提取到名为的目录中dir
creates a zipfile where test.py
would be extracted to a directory called dir
编辑:
我曾经不得不在zip文件中创建一个空目录:这是可能的。上面的代码后的
只是从zipfile中删除了文件test.py,文件消失了,但是空目录仍然存在。
I once had to create an empty directory in a zip file: it is possible. after the code above just delete the file test.py from the zipfile, the file is gone, but the empty directory stays.
这篇关于使用python将文件夹添加到zip文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!