【问题标题】:how to import and read multiple json files in pandas?如何在 pandas 中导入和读取多个 json 文件?
【发布时间】:2021-12-14 04:00:07
【问题描述】:

我正在尝试使用 python 读取多个 json 文件。 我的文件如下所示:

  • 收件箱
    • 杰克
      • message1.json
    • 布拉德
      • message1.json
    • 查尔斯
      • message1.json
    • 艾默生
      • message1.json
    • 卢克
      • message1.json

如您所见,所有的 json 文件都具有相同的名称,只是文件夹具有不同的名称。有没有办法读取收件箱并遍历每个文件夹以获取 json 文件?

到目前为止,我有这个:

path = '/messages/inbox/'
file= '/message_1.json'

并且正在考虑这样的事情:

for i in <something?> :
   new_file = path + str(i) + file

with open('new_file', 'r') as myfile:
     data=myfile.read()

obj = json.loads(data)

我知道这行不通,因为 python 需要先读取路径。如何让程序读取路径然后遍历它?

感谢您花时间阅读我的问题并尽您所能提供帮助。

【问题讨论】:

    标签: python json pandas file


    【解决方案1】:

    可以使用os.listdir("relative path to where the folders are")(take a look at the domumentation)的方法获取cwd中的所有子目录。而且您不应该使用负载来获取文件的内容,而是将文件对象传递给json.load() 方法。在你的代码中实现它是这样的:

    import os
    
    for i in os.listdir(path) :
       new_file = path + i + file
       my_file = open(new_file,"r")
       obj = json.load(my_file)
       my_file.close()
    

    【讨论】:

      猜你喜欢
      • 2019-11-25
      • 2012-10-18
      • 1970-01-01
      • 2019-08-08
      • 1970-01-01
      • 2021-12-04
      • 2019-12-08
      • 2020-11-05
      • 1970-01-01
      相关资源
      最近更新 更多