Home > Software engineering >  Why am i getting this error while trying to open json file?
Why am i getting this error while trying to open json file?

Time:01-27

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

CodePudding user response:

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:

CodePudding user response:

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)
  •  Tags:  
  • Related