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

Python批量解压目录下Zip文件时遭遇FileNotFoundError问题求助

解决指定目录下Zip文件解压的FileNotFoundError问题

错误原因

你遇到的FileNotFoundError是因为os.listdir(directory)返回的仅仅是目录里的文件名,不是完整文件路径。当你直接用这个文件名初始化ZipFile时,Python会在当前脚本的工作目录下去找这个文件,而不是你指定的目标目录D:\\Python ds and alg by mostafa,自然找不到对应的Zip文件。

修正后的代码

import os
import zipfile

directory = 'D:\\Python ds and alg by mostafa'
for file in os.listdir(directory):
    if file.endswith('.zip'):
        # 拼接完整文件路径
        zip_path = os.path.join(directory, file)
        zipfile.ZipFile(zip_path).extractall(directory)

关键修改说明

  • 使用os.path.join(directory, file)将目标目录路径和文件名拼接成完整的文件路径,确保Python能准确定位到要解压的Zip文件。
  • 若不想让解压后的文件与原Zip文件混在一起,可以给extractall指定子目录,比如extractall(os.path.join(directory, file[:-4])),这样每个Zip文件会被单独解压到以自身文件名命名的子文件夹中。

原错误代码

import os
import zipfile

directory = 'D:\\Python ds and alg by mostafa'
for file in os.listdir(directory):
    if file.endswith('.zip'):
        zipfile.ZipFile(file).extractall(directory)

原错误信息

Traceback (most recent call last):
File "D:/Python Automation Files/extract_zip_files.py", line 7, in
zipfile.ZipFile(file).extractall(directory)
File "C:\Python310\lib\zipfile.py", line 1247, in init
self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: '08_Logical_and_physical_Data_Structures.zip'

内容的提问来源于stack exchange,提问作者Mohammad Diab

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 00:48:20