Read all JSON Files in Directory in Python

Python – Read all JSON files in directory

To read all JSON files in directory in python, follow these steps.

  • Use os.listdir() function to get all the files at given directory path.
  • Use string.endswith() function to check if the extension of the file is .json.

Examples

1. Read all JSON files in given directory

In the following program, we take a directory named data which has three JSON files. We shall read all these three JSON files and print the data in them to standard output.

We will use list comprehension to consolidate all JSON files in a list.

Python Program

import os, json

path_to_json_files = 'data/'

# Get all JSON file names as a list
json_file_names = [filename for filename in os.listdir(path_to_json_files) if filename.endswith('.json')]

for json_file_name in json_file_names:
    with open(os.path.join(path_to_json_files, json_file_name)) as json_file:
        json_text = json.load(json_file)
        print(json_file_name, json_text)
Copy

Output

file3.json {'cherry': 100}
file2.json {'banana': 20}
file1.json {'apple': 25}

Summary

In this tutorial of Python Examples, we learned how to read all the JSON files in a given directory.

Related Tutorials

Code copied to clipboard successfully 👍