Python:在没有目录的情况下将文件放入存档中?

标签 python zip

我已经学习 Python 大约 3 周了,目前我正在尝试编写一个小脚本,用于按文件名中出现的关键字和日期对文件(大约 10.000)进行排序。给定日期之前的文件应添加到存档中。排序工作正常,但归档不正常

它创建一个存档——名字很好——但在存档中是文件的完整路径。 如果我打开它,它看起来像:folder1 -> folder2 -> folder3 -> files

我怎样才能改变它,使存档只包含文件而不包含整个结构?

下面是我的 zip 函数的一个片段,node 是排序前文件所在的路径,folder 是一个子文件夹,文件按关键字排序name, items 是文件按日期排序的文件夹。

我正在使用 Python 2.6

def ZipFolder(node, zipdate):
    xynode = node + '/xy'
    yznode = node + '/yz'
    for folder in [xynode,yznode]:
        items = os.listdir(folder)
        for item in items:
            itemdate = re.findall('(?<=_)\d\d\d\d-\d\d', item)
            print item
            if itemdate[0] <= zipdate:
                arcname = str(item) + '.zip'
                x = zipfile.ZipFile(folder + '/' + arcname, mode='w', compression = zipfile.ZIP_DEFLATED)
                files = os.listdir(folder + '/' + item)
                for f in files:
                    x.write(folder + '/' + item + '/' + f)
                    print 'writing ' + str(folder + '/' + item + '/' + f) + ' in ' + str(item)
                x.close()
                shutil.rmtree(folder + '/' + item)
    return

我也乐于接受任何建议和改进。

最佳答案

来自帮助(压缩文件):

 |  write(self, filename, arcname=None, compress_type=None)
 |      Put the bytes from filename into the archive under the name
 |      arcname.

所以尝试改变你的 write() 调用:

x.write(folder + '/' + item + '/' + f, arcname = f)

关于你的代码,在我看来已经足够好了,尤其是对于一个 3 周的 pythonist 来说,尽管欢迎一些评论 ;-)

关于Python:在没有目录的情况下将文件放入存档中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7007868/

相关文章:

python - 为什么 Python 3 会输出\xe3,一个额外的字符?

python - 如何使用 VisPy 库实时绘图?

python - 为什么在 init() 中声明的 Kivy 属性在使用 bind() 时会生成错误?

zip - 使用 winrar 命令行创建 zip 存档

python - 预测方法为创建的模型给出错误

python - 当多线程 python 进程运行时,操作系统开始杀死进程

java - 如何修复 org.apache.commons.compress.archivers.zip.UnsupportedZipFeatureException(epub mimetype)?

zip - zip 和 tgz 格式有什么区别?

algorithm - 文本文件中数据的顺序会影响其压缩率吗?

java - 播放压缩文件中的音频文件