【发布时间】:2021-11-17 12:57:54
【问题描述】:
我有一个文件夹,其中包含多个子文件夹,每个子文件夹包含我需要的 3-4 个文件。 我正在尝试遍历该文件夹并将每个子文件夹中的所有文件放入字典中,该字典稍后转储到 json 文件中。
到目前为止,我已经设法为单个文件执行此操作,json 文件如下所示:
这是代码:
import os
import json
myDir = "\\\iads011n\\ContinuousTesting\\DailyTesting\\REPORTS"
filelist = []
for path, subdirs, files in os.walk(myDir):
for file in files:
if (file.endswith('.xlsx') or file.endswith('.xls') or file.endswith('.XLS')) and "Release" in file and "Integrated" not in file:
filelist.append(os.path.join(file))
myDict = dict(zip(range(len(filelist)), filelist))
result=[]
for k,v in myDict.items():
result.append({'id' : k, 'name' : v})
with open('XLList.json', 'w') as json_file:
json.dump(result, json_file)
但我想要实现的是:
所以基本上我需要的是分组同一子文件夹下的所有 xls/ xlsx 文件。 主要问题是并非所有子文件夹都包含相同的项目,有些可能只有一个 xlsx 文件,另一些可能只有 3 或 4 个,等等。
【问题讨论】:
-
所以每个子文件夹会有不同的ID?您也可以布局您的目录的示例文件树吗?
-
同样在您的情况下,您正在检查
"Integrated" not in file,但在您的预期输出中,它们已包含:D 此外,"version"文件不在条件下,但在预期输出中。由于细节不清楚,我投票结束这个问题。 -
是的,所以每个子文件夹都有不同的 ID。而且,示例代码仅适用于一个文件,我必须匹配该文件,这就是为什么“集成”不在文件中。版本相同。
-
但我想要的是有一个字典/列表或任何数据类型的对象,每个对象都应该有一个 id 和每个子文件夹中 xlsx 文件的名称。
标签: python dictionary xlsx subdirectory os.walk