Here is my code. I’m trying to go through all json files in folder , pretty print them and write to output txt file.
> import json import os
>
> directory = os.listdir('D:/py/NFT/project/output/metadata/')
> for file in directory:
> with open(file) as jsonfile:
> parsed = json.load(jsonfile)
> conv = json.dumps(parsed, indent=4, sort_keys=True)
> out = open('outputfile' , 'a')
> out.write(conv)
But I’m getting an error:
Traceback (most recent call last): File "d:\py\NFT\project\m.py", line 6, in <module>
with open(file) as jsonfile: FileNotFoundError:
[Errno 2] No such file or directory: '1.json'
In a folder there is .json files – 1.json , 2.json, 3.json etc
>Solution :
os.listdir returns a list of all files in the directory, but just the file names, not the absolute path. When you open them, since they’re not in the directory your main python file is, there’s a problem.
You need to add the absolute path section at the start
import json import os
directory = os.listdir('D:/py/NFT/project/output/metadata/')
for file in directory:
with open(f"D:/py/NFT/project/output/metadata/{file}") as jsonfile:
parsed = json.load(jsonfile)
conv = json.dumps(parsed, indent=4, sort_keys=True)
out = open('outputfile' , 'a')
out.write(conv)