首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >解压缩python文件中的FileNotFoundError

解压缩python文件中的FileNotFoundError
EN

Stack Overflow用户
提问于 2022-07-26 06:41:10
回答 1查看 23关注 0票数 0

我需要自动化一些无聊的东西,其中之一就是解压缩当前目录中的所有zip文件。

这是我的密码:

代码语言:javascript
运行
复制
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)

但是,当我运行此代码时,会出现以下错误:

代码语言:javascript
运行
复制
Traceback (most recent call last):
  File "D:/Python Automation Files/extract_zip_files.py", line 7, in <module>
    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'
EN

回答 1

Stack Overflow用户

发布于 2022-07-26 06:48:55

问题似乎在于您试图提取文件'08_Logical_and_physical_Data_Structures.zip',该文件与脚本所在的文件夹不同(因为它位于您定义的目录中)。因此,在搜索它时(因为这里搜索的是正确的目录),但是在尝试提取它的行中,您不会告诉python提取位于目录中的文件。因此,如果您将代码更改为:

代码语言:javascript
运行
复制
import os
import zipfile

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

或者为了安全起见,你可以使用os.path.join(directory, file)

编辑:因为我刚刚看到了。您试图提取该文件:

D:/Python Automation Files/08_Logical_and_physical_Data_Structures.zip

但是您的代码应该提取:

D:\\Python ds and alg by mostafa\\08_Logical_and_physical_Data_Structures.zip

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73118754

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档