programing

Python: 폴더에서 여러 json 파일 읽기

luckcodes 2023. 2. 11. 23:43

Python: 폴더에서 여러 json 파일 읽기

몇 가지 읽는 법을 알고 싶습니다.json(파일 이름을 지정하지 않고 json 파일만 지정).

또, 그것들을 다른 것으로 바꿀 수도 있습니다.pandas데이터 프레임?

기본적인 예를 들어주시겠어요?

하나의 옵션은 디렉토리 내의 모든 파일을 os.listdir로 나열한 후 '.json'으로 끝나는 파일만 검색하는 것입니다.

import os, json
import pandas as pd

path_to_json = 'somedir/'
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]
print(json_files)  # for me this prints ['foo.json']

이제 판다 Data Frame을 사용할 수 있습니다.from_panders에서 json(이 시점에서 python 사전)에서 판다 데이터 프레임으로 읽을 수 있습니다.

montreal_json = pd.DataFrame.from_dict(many_jsons[0])
print montreal_json['features'][0]['geometry']

인쇄:

{u'type': u'Point', u'coordinates': [-73.6051013, 45.5115944]}

이 경우에 나는 목록에 몇 개의 jons를 추가했다.many_jsons제 목록의 첫 번째 json은 사실 몬트리올에 관한 지리 데이터를 가진 geojson입니다.저는 이미 내용을 잘 알고 있기 때문에 몬트리올의 lon/lat을 알 수 있는 '기하학'을 출력합니다.

다음 코드는 위의 모든 내용을 요약한 것입니다.

import os, json
import pandas as pd

# this finds our json files
path_to_json = 'json/'
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]

# here I define my pandas Dataframe with the columns I want to get from the json
jsons_data = pd.DataFrame(columns=['country', 'city', 'long/lat'])

# we need both the json and an index number so use enumerate()
for index, js in enumerate(json_files):
    with open(os.path.join(path_to_json, js)) as json_file:
        json_text = json.load(json_file)

        # here you need to know the layout of your json and each json has to have
        # the same structure (obviously not the structure I have here)
        country = json_text['features'][0]['properties']['country']
        city = json_text['features'][0]['properties']['name']
        lonlat = json_text['features'][0]['geometry']['coordinates']
        # here I push a list of data into a pandas DataFrame at row given by 'index'
        jsons_data.loc[index] = [country, city, lonlat]

# now that we have the pertinent json data in our DataFrame let's look at it
print(jsons_data)

이 프린트는 다음과 같습니다.

  country           city                   long/lat
0  Canada  Montreal city  [-73.6051013, 45.5115944]
1  Canada        Toronto  [-79.3849008, 43.6529206]

이 코드의 경우 디렉토리 이름 'json'에 2개의 Geojon이 있다는 것을 알면 도움이 될 것입니다.각 json의 구조는 다음과 같습니다.

{"features":
[{"properties":
{"osm_key":"boundary","extent":
[-73.9729016,45.7047897,-73.4734865,45.4100756],
"name":"Montreal city","state":"Quebec","osm_id":1634158,
"osm_type":"R","osm_value":"administrative","country":"Canada"},
"type":"Feature","geometry":
{"type":"Point","coordinates":
[-73.6051013,45.5115944]}}],
"type":"FeatureCollection"}

모듈을 사용하면 (플랫) 디렉토리를 쉽게 반복할 수 있습니다.

from glob import glob

for f_name in glob('foo/*.json'):
    ...

JSON을 직접 읽어들이는 경우pandas, 여기를 참조해 주세요.

*.json으로 끝나는 모든 파일을 특정 디렉토리에서 dict로 로드합니다.

import os,json

path_to_json = '/lala/'

for file_name in [file for file in os.listdir(path_to_json) if file.endswith('.json')]:
  with open(path_to_json + file_name) as json_file:
    data = json.load(json_file)
    print(data)

직접 사용해 보십시오.https://repl.it/@SmaMa/loadjsonfiles from folderintodict

json 파일을 읽으려면

import os
import glob

contents = []
json_dir_name = '/path/to/json/dir'

json_pattern = os.path.join(json_dir_name, '*.json')
file_list = glob.glob(json_pattern)
for file in file_list:
  contents.append(read(file))

팬더 데이터 프레임으로 변환되는 경우 팬더 API를 사용합니다.

일반적으로 발전기를 사용할 수 있습니다.

def data_generator(my_path_regex):
    for filename in glob.glob(my_path_regex):
        for json_line in open(filename, 'r'):
            yield json.loads(json_line)


my_arr = [_json for _json in data_generator(my_path_regex)]

사용하고 있다glob와 함께pandas. 아래 코드를 확인합니다.

import pandas as pd
from glob import glob

df = pd.concat([pd.read_json(f_name, lines=True) for f_name in glob('foo/*.json')])

심플하고 알기 쉬운 답변입니다.

import os 
import glob
import pandas  as pd



path_to_json = r'\path\here'
# import all files from folder which ends with .json 
json_files = glob.glob(os.path.join(path_to_json, '*.json'))

# convert all files to datafr`enter code here`ame
df = pd.concat((pd.read_json(f) for f in json_files))
print(df.head())

pathlib을 사용한 솔루션이 부족한 것 같습니다:)

from pathlib import Path

file_list = list(Path("/path/to/json/dir").glob("*.json"))

또 하나의 옵션은 PySpark Dataframe으로 읽은 후 Panda Dataframe으로 변환하는 것입니다(필요하다면 PySpark DF로 유지하는 것이 좋습니다).Spark는 기본적으로 JSON 파일이 있는 디렉토리를 메인 경로로 사용하여 각 파일을 읽거나 반복할 필요 없이 처리합니다.

# pip install pyspark
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
spark_df = spark.read.json('/some_dir_with_json/*.json')

다음으로 Panda Dataframe으로 변환하려면 다음을 수행합니다.

df = spark_df.toPandas()

언급URL : https://stackoverflow.com/questions/30539679/python-read-several-json-files-from-a-folder