简体   繁体   English

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

[英]Load and read all files json in a folder with python

The problem :问题 :

I have a series of files in a folder json_data = open("C:/Users/Desktop/soccer_data2/*.json")我在文件夹中有一系列文件json_data = open("C:/Users/Desktop/soccer_data2/*.json")

like that:像那样:

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',
             .

And i want to merge all files in one json.我想将所有文件合并到一个 json 中。 It is possible?有可能的? thanks to all谢谢大家

This is just a template that I wrote here without testing it, so it might have some bugs or typo, if anyone have comments I will appreciate it.只是我在这里写的一个模板,没有测试它,所以它可能有一些错误或错字,如果有人有意见,我将不胜感激。

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)

I have tested the below and it worked.我已经测试了以下内容并且它有效。

import os,json导入操作系统,json

path_to_json = 'C:/PR/1/' path_to_json = 'C:/PR/1/'

for file_name in [file for file in os.listdir(path_to_json) if file.endswith('.json')]: with open(path_to_json + file_name) as json_file: data = json.load(json_file) print(data) for file_name in [file for file in os.listdir(path_to_json) if file.endswith('.json')]: with open(path_to_json + file_name) as json_file: data = json.load(json_file) print(data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM