提取文件夹中的多个文件-[Erno 2]没有这样的文件或目录



我正在运行以下脚本来从目录中解压缩几个zip文件:

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:Anacondalibzipfile.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'

这可能是关键:

修改此行:

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

收件人:

dir_name = "C:/my_path/zip"

为什么
因为os.listdir正在名为"C:/my_path/zip/{name}"的目录中查找,但由于变量name尚未声明,因此该目录不存在。因此,在我的机器上触发了以下错误(尽管是Linux,因此是非Windows类型的路径(:

FileNotFoundError: [Errno 2] No such file or directory: '/devmt/services/{name}' 

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

相关内容

最新更新