我需要自动化一些无聊的东西,其中之一就是解压缩当前目录中的所有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 <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'
发布于 2022-07-26 06:48:55
问题似乎在于您试图提取文件'08_Logical_and_physical_Data_Structures.zip',该文件与脚本所在的文件夹不同(因为它位于您定义的目录中)。因此,在搜索它时(因为这里搜索的是正确的目录),但是在尝试提取它的行中,您不会告诉python提取位于目录中的文件。因此,如果您将代码更改为:
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
https://stackoverflow.com/questions/73118754
复制相似问题