Подтвердить что ты не робот

Распаковка файлов в Python

Я прочитал документацию zipfile, но не мог понять, как разархивировать файл, только как сжать файл. Как мне разархивировать все содержимое zip файла в один и тот же каталог?

4b9b3361

Ответ 1

import zipfile
with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:
    zip_ref.extractall(directory_to_extract_to)

Это в значительной степени это!

Ответ 2

Если вы используете Python 3.2 или более поздней версии:

import zipfile
with zipfile.ZipFile("file.zip","r") as zip_ref:
    zip_ref.extractall("targetdir")

Вам не нужно использовать функцию close или try/catch, поскольку она использует конструкцию менеджера контекста.

Ответ 3

Используйте метод extractall, если вы используете Python 2.6 +

zip = ZipFile('file.zip')
zip.extractall()

Ответ 4

Вы также можете импортировать только ZipFile :

from zipfile import ZipFile
zf = ZipFile('path_to_file/file.zip', 'r')
zf.extractall('path_to_extract_folder')
zf.close()

Работает в Python 2 и Python 3.

Ответ 5

Это рекурсивное решение для ZIP и RAR:

  • Просто создайте файл с кодом Python, приведенным ниже.
  • Запустите код из cmd как python filename.py
  • Он попросит вас указать абсолютный путь к файлу ZIP или RAR.
  • Получить все файлы, извлеченные в папке с тем же именем, что и файл zip.
  • Это то же самое, что функциональность Winrar, "Извлечь здесь".
  • Один дополнительный объект дается т.е. рекурсивные извлечения. если в вашем файле "a.zip" содержатся другие файлы .zip, например "b.zip", "c.zip" и т.д., то эти файлы также будут извлечены вложенным способом.
  • для поддержки RAR вам необходимо установить пакеты python для unrar и rarfile.

    pip install unrar
    pip install rarfile
    
  • Вы еще не закончили, теперь вы также должны вручную установить unrar для Windows и Linux.

    Для Linux:

    sudo apt-get install unrar
    

    Для Windows:

    Нажмите здесь, чтобы загрузить файл unrar.exe

  • Установите это.

  • Теперь получите файл unrar.exe, установленный из программных файлов.
  • Обычно расположение это:

    C:\Program Files (x86)\GnuWin32\bin\unrar.exe
    
  • Добавьте этот путь в ваши переменные пути Windows. потому что этот путь будет путём инструмента unrar, который будет использоваться во время извлечения файла RAR.

    rarfile.UNRAR_TOOL = C:\Program Files (x86)\GnuWin32\bin\unrar.exe
    

    Если все настроено, вы готовы к развертыванию.

-----------------------

#import zip file.
import zipfile
# import rarfile
import rarfile
# for path checking.
import os.path
# deleting directory.
import shutil

def check_archrive_file(loc):
    '''
    check the file is an archive file or not.
    if the file is an archive file just extract it using the proper extracting method.
    '''
    # check if it is a zip file or not.
    if (loc.endswith('.zip') or loc.endswith('.rar')):
        # chcek the file is present or not .
        if os.path.isfile(loc):
            #create a directory at the same location where file will be extracted.
            output_directory_location = loc.split('.')[0]
            # if os path not exists .
            if not os.path.exists(output_directory_location):
                # create directory .
                os.mkdir(output_directory_location)
                print(" Otput Directory " , output_directory_location)
                # extract 
                if loc.endswith('.zip'):
                    extractzip(loc,output_directory_location)
                else:
                    extractrar(loc,output_directory_location)

            else:
                # Directory allready exist.
                print("Otput Directory " , output_directory_location)
                # deleting previous directoty .
                print("Deleting old Otput Directory ")
                ## Try to remove tree; if failed show an error using try...except on screen
                try:
                    # delete the directory .
                    shutil.rmtree(output_directory_location)
                    # delete success
                    print("Delete success now extracting")
                    # extract
                    # extract 
                    if loc.endswith('.zip'):
                        extractzip(loc,output_directory_location)
                    else:
                        extractrar(loc,output_directory_location)
                except OSError as e:
                    print ("Error: %s - %s." % (e.filename, e.strerror))
        else:
            print("File not located to this path")
    else:
        print("File do not have any archrive structure.")


def extractzip(loc,outloc):
    '''
    using the zipfile tool extract here .
    This function is valid if the file type is zip only
   '''
    with zipfile.ZipFile(loc,"r") as zip_ref:
        # iterate over zip info list.
        for item in zip_ref.infolist():
            zip_ref.extract(item,outloc)
        # once extraction is complete
        # check the files contains any zip file or not .
        # if directory then go through the directoty.
        zip_files = [files for files in zip_ref.filelist if files.filename.endswith('.zip')]
        # print other zip files
        # print(zip_files)
        # iterate over zip files.
        for file in zip_files:
            # iterate to get the name.
            new_loc = os.path.join(outloc,file.filename)
            #new location
            # print(new_loc)
            #start extarction.
            check_archrive_file(new_loc)
        # close.
        zip_ref.close()


def extractrar(loc,outloc):
    '''
    using the rarfile tool extract here .
    this function is valid if the file type is rar only
   '''
   #check the file is rar or not
    if(rarfile.is_rarfile(loc)):
        with rarfile.RarFile(loc,"r") as rar_ref:
                # iterate over zip info list.
                for item in rar_ref.infolist():
                    rar_ref.extract(item,outloc)
                # once extraction is complete
                # get the name of the rar files inside the rar.
                rar_files = [file for file in rar_ref.infolist() if file.filename.endswith('.rar') ]
                # iterate
                for file in rar_files:
                    # iterate to get the name.
                    new_loc = os.path.join(outloc,file.filename)
                    #new location
                    # print(new_loc)
                    #start extarction.
                    check_archrive_file(new_loc)
                # close.
                rar_ref.close()
    else:
        print("File "+loc+" is not a rar file")




def checkpathVariables():
    '''
    check path variables.
    if unrar.exe nor present then 
    install unrar and set unrar.exe in path variable.
    '''
    try:
            user_paths = os.environ['PYTHONPATH'].split(os.pathsep)
    except KeyError:
            user_paths = []
    # iterate over paths.
    for item in user_paths:
        print("User path python variables :"+user_paths)
    # check rar tool exe present or not.
    for item in user_paths:
        # print(item)
        if("unrar.exe" in item):
            print("Unrar tool setup found PYTHONPATH")
            return
    print("Unrar tool setup not found in  PYTHONPATH")
    # print os path
    os_paths_list = os.environ['PATH'].split(';')
    # check rar tool exe present or not.
    for item in os_paths_list:
        # print(item)
        if("unrar.exe" in item):
            print("Unrar tool setup found in PATH")
            rarfile.UNRAR_TOOL = item 
            print("Unrar tool path set up complete ."+item)
            return
    print("Unrar tool setup not found in PATH")
    print("RAR TOOL WILL NOT WORK FOR YOU.")
    downloadlocation = "https://www.rarlab.com/rar/unrarw32.exe"
    print("install unrar form the link"+downloadlocation)




# run the main function
if __name__ == '__main__':
    '''
    before you run this function make sure you have installed two packages 
    unrar and rarfile.
    if not installed then 
    pip install unrar
    pip install rarfile.
    This is not only the case unrar tool should be set up.
    zip is included in standard library so do not worry about the zip file.
    '''
    # check path and variables.
    checkpathVariables()
    # Take input form the user.
    location = input('Please provide the absolute path of the zip/rar file-----> ')
    check_archrive_file(location)

-----------------------

Не паникуйте, это длинный сценарий, разделенный в основном на четыре части.

Часть 1

Убедитесь, что вы правильно установили переменную path. Этот раздел не обязателен, если вы не хотите работать с файлом RAR.

def checkpathVariables():
    '''
    check path variables.
    if unrar.exe nor present then 
    install unrar and set unrar.exe in path variable.
    '''
    try:
            user_paths = os.environ['PYTHONPATH'].split(os.pathsep)
    except KeyError:
            user_paths = []
    # iterate over paths.
    for item in user_paths:
        print("User path python variables :"+user_paths)
    # check rar tool exe present or not.
    for item in user_paths:
        # print(item)
        if("unrar.exe" in item):
            print("Unrar tool setup found PYTHONPATH")
            return
    print("Unrar tool setup not found in  PYTHONPATH")
    # print os path
    os_paths_list = os.environ['PATH'].split(';')
    # check rar tool exe present or not.
    for item in os_paths_list:
        # print(item)
        if("unrar.exe" in item):
            print("Unrar tool setup found in PATH")
            rarfile.UNRAR_TOOL = item 
            print("Unrar tool path set up complete ."+item)
            return
    print("Unrar tool setup not found in PATH")
    print("RAR TOOL WILL NOT WORK FOR YOU.")
    downloadlocation = "https://www.rarlab.com/rar/unrarw32.exe"
    print("install unrar form the link"+downloadlocation)

Часть 2

Эта функция извлекает ZIP файл. Принимает два аргумента loc и outloc. loc = "Имя файла с абсолютным путем". outloc = "Файл, в который он будет извлечен".

def extractzip(loc,outloc):
        '''
        using the zipfile tool extract here .
        This function is valid if the file type is zip only
       '''
        with zipfile.ZipFile(loc,"r") as zip_ref:
            # iterate over zip info list.
            for item in zip_ref.infolist():
                zip_ref.extract(item,outloc)
            # once extraction is complete
            # check the files contains any zip file or not .
            # if directory then go through the directoty.
            zip_files = [files for files in zip_ref.filelist if files.filename.endswith('.zip')]
            # print other zip files
            # print(zip_files)
            # iterate over zip files.
            for file in zip_files:
                # iterate to get the name.
                new_loc = os.path.join(outloc,file.filename)
                #new location
                # print(new_loc)
                #start extarction.
                check_archrive_file(new_loc)
            # close.
            zip_ref.close()

Часть 3

Эта функция извлекает файл RAR. Почти так же, как почтовый индекс.

def extractrar(loc,outloc):
        '''
        using the rarfile tool extract here .
        this function is valid if the file type is rar only
       '''
       #check the file is rar or not
        if(rarfile.is_rarfile(loc)):
            with rarfile.RarFile(loc,"r") as rar_ref:
                    # iterate over zip info list.
                    for item in rar_ref.infolist():
                        rar_ref.extract(item,outloc)
                    # once extraction is complete
                    # get the name of the rar files inside the rar.
                    rar_files = [file for file in rar_ref.infolist() if file.filename.endswith('.rar') ]
                    # iterate
                    for file in rar_files:
                        # iterate to get the name.
                        new_loc = os.path.join(outloc,file.filename)
                        #new location
                        # print(new_loc)
                        #start extarction.
                        check_archrive_file(new_loc)
                    # close.
                    rar_ref.close()
        else:
            print("File "+loc+" is not a rar file")

Часть 4

Основная функция спрашивает пользователя об абсолютном пути. Вы можете изменить его на предопределенный путь, установив значение местоположения. и закомментируйте функцию ввода.

if __name__ == '__main__':
    '''
    before you run this function make sure you have installed two packages 
    unrar and rarfile.
    if not installed then 
    pip install unrar
    pip install rarfile.
    This is not only the case unrar tool should be set up.
    zip is included in standard library so do not worry about the zip file.
    '''
    # check path and variables.
    checkpathVariables()
    # Take input form the user.
    location = input('Please provide the absolute path of the zip/rar file-----> ')
    check_archrive_file(location)

Проблемы, которые все еще присутствуют.

  • Это решение не может извлечь все типы файлов RAR.
  • Хотя он проходит проверку rarfile.is_rarfile("filename")
  • Я проверил RAR, созданный WinRAR, он выдает предупреждение и не извлекает файлы.

    [Пожалуйста, прокомментируйте, если вы можете помочь в отношении этого предупреждения и isuue]

    rarfile.RarWarning: Non-fatal error [1]: b'\r\nD:\\Kiosk\\Download\\Tutorial\\reezoo\\a.rar is not RAR archive\r\nNo files to extract\r\n
    
  • Но он может легко извлечь тип RAR4.

Ответ 6

import os 
zip_file_path = "C:\AA\BB"
file_list = os.listdir(path)
abs_path = []
for a in file_list:
    x = zip_file_path+'\\'+a
    print x
    abs_path.append(x)
for f in abs_path:
    zip=zipfile.ZipFile(f)
    zip.extractall(zip_file_path)

Это не содержит проверки для файла, если это не zip. Если папка содержит не.zip файл, это не сработает.

Ответ 7

попробуйте это:


import zipfile
def un_zipFiles(path):
    files=os.listdir(path)
    for file in files:
        if file.endswith('.zip'):
            filePath=path+'/'+file
            zip_file = zipfile.ZipFile(filePath)
            for names in zip_file.namelist():
                zip_file.extract(names,path)
            zip_file.close() 

путь: распаковать путь к файлу