2016-06-21 3 views
-2

В Python, как извлечь zip-архив при сохранении структуры папок, но исключая определенные имена файлов (типов файлов) извлечения? Например, я хочу исключить извлечения всех изображений .tif.Извлечь файлы из zip-архива, исключая определенные имена файлов

Я использую Python 3.x и модуль zipfile.

ответ

1

Пропустить фильтр members до extractall(). archive.extractall(members=(member for member in archive.namelist() if not member.endswith('.tif'))).

def extractall(self, path=None, members=None, pwd=None): 
    """Extract all members from the archive to the current working 
     directory. `path' specifies a different directory to extract to. 
     `members' is optional and must be a subset of the list returned 
     by namelist(). 
    """ 
    if members is None: 
     members = self.namelist() 

    for zipinfo in members: 
     self.extract(zipinfo, path, pwd) 
1

Прошло некоторое время с тех пор, как я использовал эту процедуру, поэтому мне пришлось ее выкопать. Вы можете протестировать/адаптироваться к вашим конкретным потребностям.

Заявление об исключении if проверяет только последние три символа для извлечения имени файла, вы можете изменить это с помощью .split('.'), чтобы проверить наличие полного расширения, так как у многих файлов теперь больше трех символов для расширения.

Это была написана для Windows, и вы можете изменить некоторые биты при работе на других операционных системах

Этот код с сохранением структуры папок, но, вероятно, не самый быстрый рутина (хотя я никогда не имел никаких жалоб:

import zipfile 


def unzip_file(zippedfile = '', targetdir = '', exclude_ext = ''): 

    if zippedfile == '': ## this is the .zip file 
     return 
    if targetdir == '': 
     targetdir = os.path.join(os.path.dirname(zippedfile), os.path.basename(zippedfile)[:-4])  
    if not os.path.exists (targetdir): 
     os.makedirs (targetdir) 

    zfile = zipfile.ZipFile(zippedfile) 

    for name in zfile.namelist(): 
     (dirName, fileName) = os.path.split(name) 
     if not dirName == '': 
      if not os.path.exists (os.path.join(targetdir, dirName)): 
       os.makedirs (os.path.join(targetdir, dirName)) 
     if fileName == '': 
      # directory 
      newDir = os.path.join(targetdir, dirName) 
      if not os.path.exists(newDir): 
       os.makedirs (newDir) 
     else: 
      # file 
      if exclude_ext == '': 
       print ('Extracting File : ' + name) 
       fd = open(os.path.join(targetdir, name), 'wb') 
       fd.write(zfile.read(name)) 
       fd.close() 
      else: 
       if not exclude_ext == name[-3:]: 
        print ('Extracting File : ' + name) 
        fd = open(os.path.join(targetdir, name), 'wb') 
        fd.write(zfile.read(name)) 
        fd.close()      
       else: 
        print ('File with extension ' + exclude_ext + ' is excluded') 
    zfile.close() 

    return 

Удачи.

Смежные вопросы