Open JSON files in different directory - Python3, Windows, pathlib
The accepted answer has a lot of redundants - re-collected generator and mixed with statement with pathlib.Path.pathlib.Path is awesome solution to handle paths especially if we want to create scripts which may work with Linux and Windows.
# modulesfrom pathlib import Pathimport json# static valuesJSON_SUFFIXES = [".json", ".js", ".other_suffix"]folder_path = Path("C:/users/user/documents")for file_path in folder_path.iterdir(): if file_path.suffix in JSON_SUFFIXES: data = json.loads(file_path.read_bytes())
Just adding modification for new users. pathlib.Path works with Python3.
Complete solution; thanks @eryksun:
from pathlib import *import jsonpath = Path("C:/foo/bar")filelist = []for f in path.iterdir(): filelist.append(f)for file in filelist: with open(str(file) as data_file: data = json.load(data_file)
This line works as well:
with file.open() as data_file: