我如何打开文件夹中的 json 文件并阅读它们或在 python 中打印它们

Posted

技术标签:

【中文标题】我如何打开文件夹中的 json 文件并阅读它们或在 python 中打印它们【英文标题】:How can i open json files in folder and read them or print them in python 【发布时间】:2021-11-29 16:10:30 【问题描述】:

我想迭代并检查文件夹中是否有新文件更新,然后读取文件,例如data.json 然后访问数据并打印它们。但我似乎无法访问它自己的文件中的数据

错误信息:使用 open(json_files) 作为文件: TypeError: 预期的 str、bytes 或 os.PathLike 对象,而不是列表

import os, json
import pandas as pd

path_to_json = '/Webservertesting/JsonFiles'
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')] #creats a lis of the files in folder
print(type(json_files))  # for me this prints ['foo.json']

for jsonfile in json_files:
    print(jsonfile)
    with open(jsonfile,json) as file:
            data = json.load(file)
            print(data)

【问题讨论】:

这能回答你的问题吗? Python: Read several json files from a folder 【参考方案1】:

试试这个:

for jsonfile in json_files:
    print(jsonfile)
    with open(os.path.join(path_to_json, jsonfile)) as file:
            data = json.load(file)
            print(data)

【讨论】:

以上是关于我如何打开文件夹中的 json 文件并阅读它们或在 python 中打印它们的主要内容,如果未能解决你的问题,请参考以下文章

打开并阅读一个txt文件? [复制]

如何使用 .net StreamReader 打开已打开的文件?

如何使用Java更新JSON文件中的嵌套JSON对象?

如何使用路径中文件中的数组序列化 JSON 数组?

如何将包含 zip 文件的 QBytesArray 加载到 QuaZip?

在 iOS 中离线打开和存储加密文档