Unzip all zipped files in a folder to that same folder using Python 2.7.5

前端 未结 4 717
小蘑菇
小蘑菇 2021-01-30 18:15

I would like to write a simple script to iterate through all the files in a folder and unzip those that are zipped (.zip) to that same folder. For this project, I have a folder

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-30 18:59

    The accepted answer works great!

    Just to extend the idea to unzip all the files with .zip extension within all the sub-directories inside a directory the following code seems to work well:

    import os
    import zipfile
    
    for path, dir_list, file_list in os.walk(dir_path):
        for file_name in file_list:
            if file_name.endswith(".zip"):
                abs_file_path = os.path.join(path, file_name)
    
                # The following three lines of code are only useful if 
                # a. the zip file is to unzipped in it's parent folder and 
                # b. inside the folder of the same name as the file
    
                parent_path = os.path.split(abs_file_path)[0]
                output_folder_name = os.path.splitext(abs_file_path)[0]
                output_path = os.path.join(parent_path, output_folder_name)
    
                zip_obj = zipfile.ZipFile(abs_file_path, 'r')
                zip_obj.extractall(output_path)
                zip_obj.close()
    

提交回复
热议问题