1

I have like 100 json file in a folder and each json file contains information like student_id, student_nationality etc. How do I use readlines for each json file using os method?

path_to_json = 'directory'
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]

When I try to loop in each file, I can't use file.readlines() as it says "Str don't have attributes readlines()”. I guess we can only use readlines if its a list type.

I need to be able to read each json file and get the information I need.

Greystormy
  • 48
  • 8
Tech
  • 65
  • 7

1 Answers1

1

Usually when you’re reading in json files, it’s best to read them in with the json library.

The code to read it in will look something like this:

import json

with open(“json_file.json”) as f:
   data = json.load(f)

And now data will be a dictionary with the data from the json file. So if you need to grab student ID, it would just be:

studentID = data[‘student_id’]

This makes it much easier to write whatever logic you need to grab the elements you want from your files

Greystormy
  • 48
  • 8