Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading all json files in a directory

I have multiple (400) json files containing a dict in a directory that I want to read and append to a list. I've tried looping over all the files in the directory like this:

path_to_jsonfiles = 'TripAdvisorHotels'
alldicts = []
for file in os.listdir(path_to_jsonfiles):
    with open(file,'r') as fi:
        dict = json.load(fi)
alldicts.append(dict)

I keep getting the following error:

FileNotFoundError: [Errno 2] No such file or directory

However, when I look at the files in the directory, it gives me all the right files.

for file in os.listdir(path_to_jsonfiles):
    print(file)

Just opening one of them with the file name works as well.

with open('AWEO-q_GiWls5-O-PzbM.json','r') as fi:
    data = json.load(fi)

Were in the loop is it going wrong?

like image 620
Lisadk Avatar asked Oct 20 '25 14:10

Lisadk


1 Answers

Your code has two errors:

1.file is only the file name. You have to write full filepath (including its folder).

2.You have to use append inside the loop.

To sum up, this should work:

alldicts = []
for file in os.listdir(path_to_jsonfiles):
    full_filename = "%s/%s" % (path_to_jsonfiles, file)
    with open(full_filename,'r') as fi:
        dict = json.load(fi)
        alldicts.append(dict)
like image 59
Ali Yılmaz Avatar answered Oct 22 '25 05:10

Ali Yılmaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!