Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading