如何从 ZIP 存档中仅提取 mp3 文件
How to extract only mp3 files from a ZIP archive
我有这个代码:
from zipfile import ZipFile
import os
import glob
inp = raw_input("Specify a ZIP archive to extract:")
with ZipFile(inp) as zf:
zf.extractall()
它工作正常,因为它提取了所有文件,但我如何提取用户指定的存档中的所有 .mp3
文件。
您可以 get a list of the names of the members in the list, and only extract 那些以 .mp3
.
后缀结尾的
要仅从 ZIP 存档中提取 MP3 文件,您可以执行以下操作:
from zipfile import ZipFile
import os
zip_file = r"c:\folder\myzip.zip"
target_folder = r"C:\Users\Fred\Desktop"
with ZipFile(zip_file, 'r') as my_zip:
mp3_files = [name for name in my_zip.namelist() if os.path.splitext(name)[1].lower() == '.mp3']
my_zip.extractall(target_folder, mp3_files)
可以使用 namelist
function. With this you can filter just those files ending with an mp3
extension. The extractall
函数获取 ZIP 文件中的文件列表,让您传递要提取的所有文件的列表(默认为所有文件)。
我有这个代码:
from zipfile import ZipFile
import os
import glob
inp = raw_input("Specify a ZIP archive to extract:")
with ZipFile(inp) as zf:
zf.extractall()
它工作正常,因为它提取了所有文件,但我如何提取用户指定的存档中的所有 .mp3
文件。
您可以 get a list of the names of the members in the list, and only extract 那些以 .mp3
.
要仅从 ZIP 存档中提取 MP3 文件,您可以执行以下操作:
from zipfile import ZipFile
import os
zip_file = r"c:\folder\myzip.zip"
target_folder = r"C:\Users\Fred\Desktop"
with ZipFile(zip_file, 'r') as my_zip:
mp3_files = [name for name in my_zip.namelist() if os.path.splitext(name)[1].lower() == '.mp3']
my_zip.extractall(target_folder, mp3_files)
可以使用 namelist
function. With this you can filter just those files ending with an mp3
extension. The extractall
函数获取 ZIP 文件中的文件列表,让您传递要提取的所有文件的列表(默认为所有文件)。