简体   繁体   English

使用 Python 无法仅解压缩.mdf 文件

[英]Using Python unable to unzip .mdf files only

Using Python trying to unzip.mdf files from multiple zip files in the same directory.使用 Python 尝试从同一目录中的多个 zip 文件中解压缩.mdf 文件。 The below code is not finding any.mdf files in the.zip files, because of how I have written it.下面的代码在 .zip 文件中找不到任何 .mdf 文件,因为我是这么写的。 It is looking at the.zip file not what is in them (I think).它正在查看.zip 文件而不是其中的内容(我认为)。 But I'm not sure how to amend it to get what I need.但我不确定如何修改它以获得我需要的东西。 New to Python clearly.显然是 Python 的新手。

import zipfile
import os

os.chdir(working_directory)

for file in os.listdir(working_directory):
    if zipfile.is_zipfile(file):
        with zipfile.ZipFile(file) as item:
            if file.endswith('.mdf'):
                item.extractall()

You are checking if file - which is the zip file - ends with .mdf or not.您正在检查file (即 zip 文件)是否以.mdf结尾。 Which obviously won't work.这显然行不通。

You need to look inside the zip file.您需要查看 zip 文件的内部。 Once you have the zipfile open, you can call the namelist() method to get the list of names of the members of the zip file.打开 zipfile 后,您可以调用namelist()方法来获取 zip 文件成员的名称列表。

import zipfile
import os

os.chdir(working_directory)

for file in os.listdir(working_directory):
    if zipfile.is_zipfile(file):
        with zipfile.ZipFile(file) as item:
            for member in item.namelist():  # go through members of the zip file
                if member.endswith('.mdf'):
                    item.extract(member)    # extract only the mdf file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM