如何只压缩文件夹内的文件而不压缩子文件夹?

时间:2016-08-30 12:08:55

标签: python windows zipfile

我有一个文件夹结构:

/sample/debug/
    --debug.exe
    --sample.exe
    --sample.pdb
    --debug.pdb
    --sample.dll
    --debug.dll
    /config
        --sample.txt
        --new.txt
    /general
        --general.txt
        --code.txt

所以,我想要的只是将文件压缩到debug中,而不是像/ config和/ general这样的子文件夹。我尝试如下:

import zipfile
import os

def append( dir_name ):
    ret_val = []
    fileList = []
    for file in os.listdir(dir_name):
        try:
            dirfile = os.path.join(dir_name, file)
        except Exception:
            err = sys.exc_info()
            print ("Error!", err)
        fileList.append(dirfile)
        ret_val = fileList
    return ret_val

def zip( fileList, archive, root ):
    ret_val = 0
    try:
        zip_folder_contents = zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED)
    except Exception:
        err = sys.exc_info()
        print ("Error!",err)
        exit( 1 )
    for filename in fileList:
        zip_folder_contents.write(filename,
                filename[len(root):].lstrip(os.path.sep).lstrip(os.path.altsep))
    zip_folder_contents.close()
    return ret_val

make(append_files_in_zipfolder("D:/sample/debug"), "debug.zip",
                               "D:/sample/debug")

现在,当我执行上面的操作时,由于权限被拒绝而得到错误" D:/ sample / debug \\ config"。因此,我无法删除此错误,因此我认为只包含zip文件夹中的文件并排除子文件夹。那么,无论如何如何做到这一点或某种方式我可以删除我得到的这个权限相关的错误。请建议。

2 个答案:

答案 0 :(得分:2)

您可以使用以下命令从文件夹中获取所有文件而无需进入子文件夹:

import datetime
import zipfile

def print_info(archive_name):
""" Print information from zip archive"""
zf = zipfile.ZipFile(archive_name)
for info in zf.infolist():
    print info.filename
    print '\tComment:\t', info.comment
    print '\tModified:\t', datetime.datetime(*info.date_time)
    print '\tSystem:\t\t', info.create_system, '(0 = Windows, 3 = Unix)'
    print '\tZIP version:\t', info.create_version
    print '\tCompressed:\t', info.compress_size, 'bytes'
    print '\tUncompressed:\t', info.file_size, 'bytes'
    print

print 'creating archive'
zf = zipfile.ZipFile('debug.zip', mode='a', compression=zipfile.ZIP_DEFLATED)
inputdir = '/sample/debug/'
filestozip = getfilesfrom(inputdir)
for afile in filestozip:
    print('adding ' + afile + ' to zipfile debug.zip')
    zf.write(os.path.join(inputdir, afile), afile)

print 'closing'
zf.close()

print
print_info('debug.zip')

然后您可以简单地运行(如documentation中所述):

 Pattern p = Pattern.compile("a*b");
 Matcher m = p.matcher("aaaaab");
 boolean b = m.matches();

答案 1 :(得分:0)

以下内容使用了新的ZipFile上下文管理器:

from zipfile import ZipFile

def zip_folder(zip_name, folder):
    with ZipFile(zip_name, 'w') as myzip:
        for entry in os.listdir(folder):
            if os.path.isfile(entry):
                myzip.write(os.path.join(folder, entry), arcname=entry)

zip_folder(r'D:\output.zip', r'D:\sample\debug')