Python:在没有目录的情况下将文件放入存档中? [英] Python: Getting files into an archive without the directory?

查看:32
本文介绍了Python:在没有目录的情况下将文件放入存档中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been learning python for about 3 weeks now, and I'm currently trying to write a little script for sorting files (about 10.000) by keywords and date appearing in the filename. Files before a given date should be added to an archive. The sorting works fine, but not the archiving

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

It creates an archive - the name is fine - but in the archive is the complete path to the files. If i open it, it looks like: folder1 -> folder2 -> folder3 -> files.

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

How can I change it such that the archive only contains the files and not the whole structure?

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

Below is a snippet with my zip function, node is the path where the files were before sorting, folder is a subfolder with the files sorted by a keyword in the name, items are the folders with files sorted by date.

我使用的是 Python 2.6

I am using 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

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

I am also open to any suggestions and improvements.

推荐答案

来自帮助(zipfile):

From help(zipfile):

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

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

So try changing your write() call with:

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

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

About your code, it seems to me good enough, especially for a 3 week pythonist, although a few comments would have been welcomed ;-)

这篇关于Python:在没有目录的情况下将文件放入存档中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆