从文件列表中读取特定的json键,并将其另存为新文件

时间:2020-07-14 16:41:06

标签: python json

我是python的新手,我正在执行的任务是从本地目录中的json文件列表中提取特定密钥。我想提取键/值“数据”并将其保存为新文件(具有现有文件名),然后对所有其他文件重复该操作。

{
    "link": "",
    "site": "",
    "date": "1593534296",
    "filename": "first",
    "size": 728,
    "time": "0",
    "language": "java",
    "data": "",
    "rule": [
        "matched"
    ]
}

import json
dirpath = r'\path'
output = []
files = os.listdir(dirpath)
for filename in files:
    with open(dirpath + '/' + filename , encoding="utf-8") as afile:
        output.append({'filename': filename, 'data': afile.read()})
        afile.close()

我首先打开文件并逐个读取它们。但是,我只能读取整个数据。我能否获得有关如何仅读取密钥“数据”并将其保存在新文件中的帮助?谢谢

2 个答案:

答案 0 :(得分:0)

只需使用:

for filename in files:
    with open(dirpath + '/' + filename , encoding="utf-8") as afile:
        json_obj = json.load(afile)  # uses the json library to parse the file
        output.append({'filename': filename, 'data': json_obj['data']})  # gets only the value of the data attribute
        # you do not need to close the file here, the "with" statement does that for you
    # the file is already closed here

答案 1 :(得分:0)

如果您不想读取整个JSON文件,则可以逐行循环,替换":,字符并在返回后返回该行按下键:

    with open(YOUR_FILE, "r") as f:
        for line in f:
            a = line.replace("\"", "").replace(":", "").replace(",", "").split()
            if a[0] == "data":
                return a