Skip to main content
 首页 » 编程设计

Python ZipFile 返回提取的文件路径和名称

2025年05月04日14mayingbao

我有这个当前代码可以将 archive 的内容解压缩到 extract_dir。但是,我不知道如何获取提取文件的提取文件路径和名称。

if archive.endswith((".zip")): 
    zip_ref = zipfile.ZipFile(archive, 'r') 
    zip_ref.extract(extract_dir) 
    zip_ref.close() 

例如,如果存档名为 test.zip 并且 ZipFile 提取内容 test.exe 我想获取 C:/windows/users/admin/downloads/test.exe 到变量中?

编辑:抱歉,我不清楚,在 zipfile 的源代码中targetpath 被返回我想知道我怎样才能得到这个?

请您参考如下方法:

这是解决方案,虽然我不能接受 2 天的答案。

if archive.endswith((".zip")): 
    print "example.jpg" 
    zip_ref = zipfile.ZipFile(archive, 'r') 
    extracted = zip_ref.namelist() 
    zip_ref.extractall(extract_dir) 
    zip_ref.close() 
    extracted_file = os.path.join(extract_dir, extracted[0])