0

我需要帮助编辑以下压缩目录内容的脚本。我的最终目标是创建一个脚本,该脚本将查看 C:\Test(其中将有多个目录)并使用 C:\Test 中每个目录的内容创建一个新的 zip 文件。棘手的部分是我需要路径是 C:\ 即使目录的真实路径是 C:\Test。这是可能的还是我在做梦?

谢谢

import zipfile, os

def makeArchive(fileList, archive):

    try:
        a = zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED)
        for f in fileList:
            print "archiving file %s" % (f)
            a.write(f)
        a.close()
        return True
    except: return False

def dirEntries(dir_name, subdir, *args):

    fileList = []
    for file in os.listdir(dir_name):
        dirfile = os.path.join(dir_name, file)
        if os.path.isfile(dirfile):
            if not args:
                fileList.append(dirfile)
            else:
                if os.path.splitext(dirfile)[1][1:] in args:
                    fileList.append(dirfile)
        # recursively access file names in subdirectories
        elif os.path.isdir(dirfile) and subdir:
            print "Accessing directory:", dirfile
            fileList.extend(dirEntries(dirfile, subdir, *args))
    return fileList

if __name__ == '__main__':
    folder = r'C:\test'
    zipname = r'C:\test\test.zip'
    makeArchive(dirEntries(folder, True), zipname)
4

1 回答 1

0

您可以更改存档中文件的路径,如下所示:

a.write(PATH_ON_FILESYSTEM, 
        DESIRED_PATH_IN_ARCHIVE
)
于 2013-03-06T00:24:36.760 回答