我该如何创建拉链?

时间:2017-03-23 21:14:28

标签: boto zipfile boto3

如何添加文件并压缩文件夹?

到目前为止,使用zipfile,我可以创建一个zip。

1 个答案:

答案 0 :(得分:1)

  

如何创建文件夹以添加文件并压缩文件夹?

您可以按照以下步骤执行操作:

要创建文件夹,请使用os.mkdir,如下所示:

import os
os.mkdir('spam') # your folder name

然后您可以向其中写入文件或使用shutil.copy制作现有文件的副本。

# to write files:
with open('./spam/eggs.txt', 'w') as fp: # creates a text file in spam named eggs.txt
    fp.write('hello') # write hello

# to copy files
import shutil
shutil.copy('eggs.txt', './spam/eggs.txt') # copy eggs.txt from the current working dir to spam folder

然后压缩文件夹,你有正确的想法,像这样使用zipfile

from zipfile import ZipFile, ZIP_DEFLATED

zipfp = ZipFile('spam.zip', 'w', ZIP_DEFLATED) # create a new zip file named spam.zip

for root, dirname, files in os.walk('./spam'): # walk in the spam folder
    [zipfp.write(os.path.join('./spam',file)) for file in files] # write them to the zip file
zipfp.close()

一个完整的例子:

import os
from zipfile import ZipFile, ZIP_DEFLATED
os.mkdir('spam')
with open('./spam/eggs.txt', 'w') as fp: 
    fp.write('hello')
with ZipFile('spam.zip', 'w', ZIP_DEFLATED) as zipfp:
    for root, dirname, files in os.walk('./spam'): 
        [zipfp.write(os.path.join('./spam',file)) for file in files] 

此代码的结果是生成一个名为spam.zip的压缩文件夹,在zip文件中,有一个名为eggs.txt的txt文件,其中包含文本'hello'

澄清OP:

[zipfp.write(os.path.join('./spam',file)) for file in files]

相当于:

for file in files:
     zipfp.write(os.path.join('./spam',file))

使用 list comprehension 编写它只是更简单。