Python 3.x 提取文件夹中的多个文件-[Errno 2]没有此类文件或目录

Python 3.x 提取文件夹中的多个文件-[Errno 2]没有此类文件或目录,python-3.x,zipfile,Python 3.x,Zipfile,我正在运行以下脚本从一个目录解压几个ZipFile: import os from zipfile import ZipFile dir_name = f"C:/my_path/zip/{name}" def main(): for item in os.listdir(dir_name): with ZipFile(item, 'r') as zipObj: listOfFileNames = zipObj.namelist()

我正在运行以下脚本从一个目录解压几个ZipFile:

import os
from zipfile import ZipFile

dir_name = f"C:/my_path/zip/{name}"

def main():

    for item in os.listdir(dir_name):
        with ZipFile(item, 'r') as zipObj: 
            listOfFileNames = zipObj.namelist()
            for fileName in listOfFileNames: 
                if fileName.endswith('.csv'):
                    for i in fileName:
                        zipObj.extract(fileName, f"C:/my_path/csv/{name}")

if __name__ == '__main__':
    main()
关键是我已经确认了一百次zip文件存储在正确的路径中,但我无法运行脚本,但我在另一台计算机上成功地运行了(?)

我做错了什么

编辑: 这是完整的错误消息:

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-6-7f26de4464fe> in <module>
     18 
     19 if __name__ == '__main__':
---> 20     main()

<ipython-input-6-7f26de4464fe> in main()
     10 
     11     for item in os.listdir(dir_name): # Iterate over the zip file
---> 12         with ZipFile(item, 'r') as zipObj: # Create a ZipFile Object and load sample.zip in it
     13             listOfFileNames = zipObj.namelist() # Get a list of all archived file names from the zip
     14             for fileName in listOfFileNames: # Iterate over the file names

C:\Anaconda\lib\zipfile.py in __init__(self, file, mode, compression, allowZip64)
   1111             while True:
   1112                 try:
-> 1113                     self.fp = io.open(file, filemode)
   1114                 except OSError:
   1115                     if filemode in modeDict:

FileNotFoundError: [Errno 2] No such file or directory: 'my_file.zip'
FileNotFoundError回溯(最近一次调用)
在里面
18
19如果uuuu name uuuuuu=='\uuuuuuu main\uuuuuuuuu':
--->20主要内容()
大体上
10
11对于os.listdir(目录名)中的项:#迭代zip文件
--->12将ZipFile(项目“r”)作为zipObj:#创建一个ZipFile对象并在其中加载sample.zip
13 listOfFileNames=zipObj.namelist()#从zip文件中获取所有存档文件名的列表
14对于listOfFileNames中的文件名:#迭代文件名
C:\Anaconda\lib\zipfile.py in uuuu init_uuuuu(self、file、mode、compression、allowZip64)
1111虽然正确:
1112尝试:
->1113 self.fp=io.open(文件、文件模式)
1114除操作错误外:
1115如果文件模式为modeDict:
FileNotFoundError:[Errno 2]没有这样的文件或目录:“my_file.zip”
这可能是关键:

修改这一行:

dir_name = f"C:/my_path/zip/{name}"
致:

为什么?
因为
os.listdir
正在查找名为
“C:/my_path/zip/{name}”
的目录,但它不存在,因为变量
name
尚未声明。因此,下面的错误在我的机器上触发(虽然是Linux,因此是非Windows类型路径):


然后,在函数的其余部分应用此逻辑,并可能使用
os.path.join
将路径和文件名缝合在一起。

您不应该硬编码路径,请查看可能的重复,我没有看到名为
name
的变量。但是,您在f字符串中引用了它。事实上,变量
name
是从代码的另一部分继承的,我在代码的另一部分中进行了一次刮取以加载zip文件。
dir_name = "C:/my_path/zip"
FileNotFoundError: [Errno 2] No such file or directory: '/devmt/services/{name}'