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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With