打开多个 json 个文件并单独阅读

opening multiple json files and reading individually

python 和 json 的新手。您将如何使用“with open”打开几个 json 文件,然后单独阅读。代码如下:

def read_json_file(filename):
      
    with open("File1location/income","file2location/weather", "file3location/sun", 'r') as fp:
        income = json.loads(fp.read())
    
    return data 
income = read_json_file(income)

print(len(income))

我需要打印每个文件的长度,但我该如何隔离每个文件?

谢谢

open 不允许您传递多个文件名 - 您总是打开一个文件(请参阅文档进行确认)。

在处理 Python 中的文件路径时,我强烈建议使用 pathlib 库并导入 Path class.

因此,例如,您需要一个列表(或通常是 array-like 结构),其中存储了所有 json 路径。然后你可以这样写:

import json
from pathlib import Path

json_paths = [Path("Fle1location/income.json") Path("file2location/weather.json"), Path("file3location/sun.json"))]

for path in json_paths:
    with open(path, 'r') as f:
        income = json.load(f)
        print(len(income))

创建functions/methods时使用return关键字。

编辑

如果您想编写一个函数,我会编辑上面的代码片段:

def main():
    for path in json_paths:
        read_json_file(path)


def read_json_file(path):
    with open(path, 'r') as f:
        income = json.load(f)
        print(len(income))


if __name__ == "__main__":
    main()

重要的是要记住,拥有一个既 returns 又具有副作用(即 print )的函数被认为是一种不好的做法。 function/method/class 应该有一个单一的、明确定义的职责(参见单一职责原则)。所以在这种情况下,我只是添加了副作用而没有返回任何东西。

要打印文件的大小,只需执行此操作。无需打开或阅读它们:

import os 

for file in 'File1location/income', 'File2location/weather', 'File3location/sun':
    print(f'{file} {os.path.getsize(file)} bytes')