You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python自学:Zip文件提取至缓存目录的问题及解决

问题:提取Zip文件内容到缓存目录失败的解决办法

我正在自学Python,尝试将Zip文件中的内容提取到缓存目录中,但发现仅成功创建了缓存目录,却未将Zip内的文件写入其中,请问有什么正确实现的建议?

原始代码

import os, shutil
from zipfile import ZipFile

path = os.getcwd()
print(path)
cache = os.path.join(path, "files/cache")
print(cache)                                                      
data_path = os.path.join(path, "files/data.zip")
print(data_path)

def clean_cache():
    if os.path.exists(cache):
        shutil.rmtree(cache)
    os.mkdir("files/cache") 

clean_cache()

def cache_zip(zip_path, cache):
    if not os.path.exists(cache):
        os.makedirs(cache)
    with ZipFile(zip_path, 'r') as datazip:
        datazip.extractall(zip_path)

    return

问题分析

原始代码的核心错误出在cache_zip函数:调用extractall时传入的参数是Zip文件自身的路径zip_path,而非目标缓存目录cache,导致文件根本不会被提取到指定的缓存文件夹里。另外clean_cache函数创建目录用了相对路径"files/cache",如果后续代码改变当前工作目录,这行可能引发路径错误,建议改用之前定义好的cache变量,保持路径一致性。

修改后的可运行代码

def cache_zip(zip_path, cache_path):
    with ZipFile(zip_path, 'r') as datazip:
        datazip.extractall(cache_path)

同时可以优化clean_cache函数避免路径问题:

def clean_cache():
    if os.path.exists(cache):
        shutil.rmtree(cache)
    os.mkdir(cache) 

内容的提问来源于stack exchange,提问作者Rhomekso Azwar Mekso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 11:05:24