Python - 搜索文件& ZIP,跨多个目录

时间:2010-11-24 23:19:04

标签: python search recursion zip

这是我第一次将一些代码组合在一起形成一个我需要的实用程序(我是一个交易设计师),虽然我觉得我很接近,但我遇到以下麻烦工作

我经常需要压缩扩展名为.COD的文件,这些文件位于我创建的目录结构中。例如,结构可能如下所示:

(单根文件夹) - > (多个文件夹) - > (两个文件夹) - > (一个文件夹) - > COD文件

我需要将所有COD文件压缩到COD.zip中,并将该zip文件放在当前文件所在的目录之上。例如,文件夹结构看起来像这样:

EXPORT文件夹 - > 9800文件夹 - > 6文件夹 - > OTA文件夹(+新COD.zip) - > COD文件

我的问题 -

首先,它创建的COD.zip似乎适合其中的COD文件但是当我解压缩它时,里面只有1个.cod但是该ZIP的文件大小是所有COD压缩的大小一起。

第二,我需要将COD文件压缩为无任何文件夹结构 - 直接在COD.zip中。目前,我的脚本创建了一个完整的目录结构(以“users / mysuername / etc etc”开头)。

任何帮助都会非常感激 - 并且在我努力学习时解释得更好:)

感谢。

import os, glob, fnmatch, zipfile


def scandirs(path):
for currentFile in glob.glob( os.path.join(path, '*') ):
    if os.path.isdir(currentFile):
        scandirs(currentFile)
    if fnmatch.fnmatch(currentFile, '*.cod'):
            cod = zipfile.ZipFile("COD.zip","a")
            cod.write(currentFile)


scandirs(os.getcwd())

2 个答案:

答案 0 :(得分:1)

对于问题#1,我认为您的问题可能就是这一部分:

cod = zipfile.ZipFile("COD.zip","a")
cod.write(currentFile)

每次编写新文件时,您都会创建一个新的zip(并可能覆盖现有的zip)。相反,您希望为每个目录创建一次zip,然后重复附加到它(参见下面的示例)。

对于问题#2,您的问题是在将文件名写入存档时可能需要展平文件名。一种方法是在os.chdir中使用scandirs来查看CD中的每个目录。一种更简单的方法是使用os.path模块拆分文件路径并获取基本名称(没有路径的文件名),然后您可以使用第二个参数cod.write来更改获取的文件名放入实际的拉链(见下面的例子)。

import os, os.path, glob, fnmatch, zipfile

def scandirs(path):

   #zip file goes at current path, then up one dir, then COD.zip
   zip_file_path = os.path.join(path,os.path.pardir,"COD.zip")
   cod = zipfile.ZipFile(zip_file_path,"a") #NOTE: will result in some empty zips at the moment for dirs that contain no .cod files

   for currentFile in glob.glob( os.path.join(path, '*') ):
      if os.path.isdir(currentFile):
         scandirs(currentFile)
      if fnmatch.fnmatch(currentFile, '*.cod'):
         cod.write(currentFile,os.path.basename(currentFile))

   cod.close()
   if not cod.namelist(): #zip is empty
      os.remove(zip_file_path)

scandirs(os.getcwd())

因此,创建一次zip文件,在展平文件名时重复附加,然后关闭它。你还需要确保你打电话给你,否则你可能无法写下你的所有文件。

我目前没有很好的方法在本地进行测试,所以请随意尝试并报告。我敢肯定我可能会破坏一些东西。 ; - )

答案 1 :(得分:1)

以下代码具有相同的效果,但更具可重用性,并且不会创建多个zip文件。

import os,glob,zipfile

def scandirs(path, pattern):
    result = []
    for file in glob.glob( os.path.join( path, pattern)):
        if os.path.isdir(file):
            result.extend(scandirs(file, pattern))
        else:
             result.append(file)
     return result


zfile = zipfile.ZipFile('yourfile.zip','w')
for file in scandirs(yourbasepath,'*.COD'):
    print 'Processing file: ' + file
    zfile.write(file)                   # folder structure
    zfile.write(file, os.path.split(file)[1])   # no folder structure

zfile.close()
相关问题