【问题标题】:Python: Getting files into an archive without the directory?Python:在没有目录的情况下将文件放入存档中?
【发布时间】:2011-10-23 21:15:35
【问题描述】:

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

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

如何更改它以使存档仅包含文件而不包含整个结构?

下面是我的 zip 函数的 sn-p,node 是排序前文件所在的路径,folder 是一个子文件夹,文件按名称中的关键字排序,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

我也愿意接受任何建议和改进。

【问题讨论】:

    标签: python zipfile


    【解决方案1】:

    来自帮助(zipfile):

     |  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 来说,虽然一些 cmets 会受到欢迎 ;-)

    【讨论】:

    • 不是 cmets 而是文档字符串。解释函数的作用和用途,而不是它的工作原理,文档字符串对此最有用。
    • @Jan Hudec: 使用 docstring 你的意思是这样的: def ZipFolder(node, zipdate): """ 压缩 'node' 的子文件夹中早于 'zipdate' 的文件"""跨度>
    • @rny:是的。这是在 python 中记录函数的标准方式。
    • 摆脱丑陋的加入。 x.write(folder, item, f, arcname = f, sep='/')
    • 虽然@Springfield 在技术上是不正确的,但使用起来似乎更正确:x.write(os.path.join(folder,item,f),arcname=f)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2015-05-07
    • 2010-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多