'Why am i getting this error while trying to open json file?
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 1:[1]
It's not strange at all. The file names returned by os.listdir are just the file names, not the path. You have to add the path:
import json import os
path = 'D:/py/NFT/project/output/metadata/'
for file in os.listdir(path):
with open(os.path.join(path,file)) as jsonfile:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tim Roberts |
