如何使用python提取文件夹中的所有.zip扩展名而不保留目录?

时间:2018-09-25 03:12:15

标签: python extract

这是我的代码,我不知道如何将每个.zip循环到一个文件夹中,请帮助我:我希望将5个zip文件的所有内容提取到一个文件夹中,而不包括目录名称

import os
import shutil
import zipfile
my_dir = r"C:\\Users\\Guest\\Desktop\\OJT\\scanner\\samples_raw"

my_zip = r"C:\\Users\\Guest\\Desktop\\OJT\\samples\\001-100.zip"
with zipfile.ZipFile(my_zip) as zip_file:
zip_file.setpassword(b"virus")
for member in zip_file.namelist():
    filename = os.path.basename(member)
    # skip directories
    if not filename:
        continue

    # copy file (taken from zipfile's extract)
    source = zip_file.open(member)
    target = file(os.path.join(my_dir, filename), "wb")
    with source, target:
        shutil.copyfileobj(source, target)

2 个答案:

答案 0 :(得分:0)

重复的问题,请参考下面的链接。

How to extract zip file recursively in Python n

答案 1 :(得分:0)

您要寻找的是glob。可以这样使用:

#<snip>
import glob

#assuming all your zip files are in the directory below.
for my_zip in glob.glob(r"C:\\Users\\Guest\\Desktop\\OJT\\samples\\*.zip"):
    with zipfile.ZipFile(my_zip) as zip_file:
        zip_file.setpassword(b"virus")
        for member in zip_file.namelist():
            #<snip> rest of your code here.