我有一个 json 文件的文件夹,我想解析它以查找特定的键值对。然后将这些对附加到字典中,然后将该字典(作为 json 行)输出到新的 json 文件。我目前无法获取文件夹中的文件进行解析,更不用说将解析的数据传输到字典中进行打印。这是我的代码:
import json, os
FbDict=[]
topdir=os.getcwd()
def main():
for root, dirs, files in os.walk(topdir):
for f in files:
if f.lower().endswith((".json")):
json_data = open(f, 'r+').read().decode("utf-8")
jdata = json.loads(json_data)
fname=f.split(".json")[0]
for k, v in jdata.items():
if isinstance(v, dict):
try:
dataFormat = {"created_at":v['data'][0]['created_time'],"user":v['data'][0]['from']['id'],
"id":v['data'][0]['id'],"name":v['data'][0]['from']['name'],"text":v['data'][0]['message']}
FbDict.append(json.dumps(dataFormat, separators=(',', ':')))
except KeyError:
continue
if __name__ == '__main__':
main()
with open ('fbFile', 'w') as f:
f.write(FbDict)
最佳答案
这是 Python 文档中您缺少的部分:
http://docs.python.org/2/library/os.html#os.walk
Note that the names in the lists contain no path components. To get a full path (which begins with top) to a file or directory in dirpath, do
os.path.join(dirpath, name)
.
现在您只是迭代文件
,这是没有任何路径信息的裸文件名。添加路径信息,您应该不再收到那些“找不到文件”错误。
关于python - 如何遍历并解析 json 文件的文件夹然后输出到单个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21728940/