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

前端 未结 4 712
小蘑菇
小蘑菇 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:58

    I think this is shorter and worked fine for me. First import the modules required:

    import zipfile, os
    

    Then, I define the working directory:

    working_directory = 'my_directory'
    os.chdir(working_directory)
    

    After that you can use a combination of the os and zipfile to get where you want:

    for file in os.listdir(working_directory):   # get the list of files
        if zipfile.is_zipfile(file): # if it is a zipfile, extract it
            with zipfile.ZipFile(file) as item: # treat the file as a zip
               item.extractall()  # extract it in the working directory
    

提交回复
热议问题