python读取json文件转化为list_Python从所有子目录读取JSON文件
I have a following folder structure:
Directory
- Subdirectory 1:
file.json
- Subdirectory 2:
file.json
- Subdirectory 3:
file.json
- Subdirectory 4:
file.json
How do I read these JSON files using Pandas?
解決方案
You could do the following:
import glob, os
working_directory = os.getcwd()
sub_directories = [active_directory + "/" + x for x in os.listdir(working_directory) if os.path.isdir(active_directory + "/"+x)]
all_json_files = []
for sub_dir in sub_directories:
os.chdir(sub_dir)
for file in glob.glob("*.json"):
all_json_files.append(sub_dir + "/" + file)
#Get back to original working directory
os.chdir(working_directory)
list_of_dfs = [pd.read_json(x) for x in all_json_files]
From there, if all json files have the same structure, you could concatenate them to get one single dataframe:
final_df = pd.concat(list_of_dfs)
總結(jié)
以上是生活随笔為你收集整理的python读取json文件转化为list_Python从所有子目录读取JSON文件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 设备树与驱动的关系_裸机程序如何驱动硬件
- 下一篇: python单例_Python单例模式