使用python加载和读取文件夹中的所有文件json

2024-04-27 18:36:55 发布

您现在位置:Python中文网/ 问答频道 /正文

问题是:

我在文件夹中有一系列文件json_data = open("C:/Users/Desktop/soccer_data2/*.json")

像这样:

a-01.json
a-02.json
a-03.json

a-01.json :

{'blabla': '127',
 'blabla': 'Sun,,26,Oct,2014',
 'events': [{'outcome': 'save',
             'playerId': 124,
             'position': ['0,50'],
             'teamId': 16,
             'timestamp': 294,
             'type': 'goal_keeping'},
            {'outcome': 'save',
             'playerId': 434,
             'position': ['0,50'],
             'teamId': 19,
             'timestamp': 744,
             'type': 'goal_keeping'},


a-02.json :
{'away_team': '112',
 'date': 'Sun,,27,Oct,2014',
 'events': [{'outcome': 'save',
             .

我想将所有文件合并到一个json中。 有可能吗? 感谢大家


Tags: 文件jsonsavetypepositionkeepingeventstimestamp
1条回答
网友
1楼 · 发布于 2024-04-27 18:36:55

这只是我在这里编写的一个模板,没有经过测试,因此可能有一些错误或打字错误,如果有人有意见,我将不胜感激。

import os # for manipulates files and subdirectories
import json # handle json files

json_folder_path = os.path.join("C","Users","Desktop","soccer_data2")
# In order to get the list of all files that ends with ".json"
# we will get list of all files, and take only the ones that ends with "json"
json_files = [ x for x in os.listdir(json_folder_path) if x.endswith("json") ]
json_data = list()
for json_file in json_files:
    json_file_path = os.path.join(json_folder_path, json_file)
    with open (json_file_path, "r") as f:
        json_data.append(json.load(f))

# now after iterate all the files, we have the data in the array, so we can just write it to file
output_path = os.path.join(json_folder_path,"output.json")
with open (output_path, "w") as f:
    json.dump(json_data, f)

相关问题 更多 >