opening multiple json files and reading individually

Viewed 120

New to python and json. How would you go about opening several json files with "with open", then reading individually. Code below:

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))

I need to print the length of each file, but how would I go about isolating each file?

Thanks

3 Answers

To print the size of your files just do this. There's no need to open or read them:

import os 

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

open doesn't let you pass multiple file names - you always open a single file (see the docs for confirmation).

When dealing with file paths in Python I highly suggest to use the pathlib library and import the Path class.

So you need, for instance, a list (or in general an array-like structure) where you have stored all of your json paths. Then you can write something like this:

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))

The return keyword is used when creating functions/methods.

EDIT

I edit the snippet above in case you want to write a function:

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()

It is important to remember that it is considered a bad practice to have a function that both returns something and has a side effect (i.e., print). A function/method/class should have one single, well defined, responsibility (see Single Responsibility Principle). So in this case I have just added the side effect without returning anything.

Related