2

I am working on a dictionary project. So, I downloaded a JSON file and placed it on my desktop. I tried to import it into my Python file but it says the file is not found.

FileNotFoundError: [Errno 2] No such file or directory: 'data.json'

Here's my code:

import json

data = json.loads(open('data.json'))
print(data)
4
  • For code to work, your python code should also be on Desktop folder. Please check if it is so. Commented Apr 25, 2020 at 6:00
  • where is your python script file placed? Commented Apr 25, 2020 at 6:02
  • adding to @gautamits the open('data.json') accepts complete path of the json file so you may also provide absolute path of json file regardles of where your code is located. Commented Apr 25, 2020 at 6:04
  • Yes @PavanKumarTS, thanks for clarifying, that as well. Commented Apr 25, 2020 at 6:05

1 Answer 1

1

You can use os.path.expanduser to get the home directory of the current user and then using os.path.join you can obtain the full path to data.json located in Desktop directory.

Use:

import os
import json

filepath = os.path.join(os.path.expanduser("~"), "Desktop", "data.json") 
with open(filepath) as file:
    data = json.load(file)
    print(data)
Sign up to request clarification or add additional context in comments.

2 Comments

@HenryWoody Not required. I've used json.load instead of json.loads.
Ah, you're right. (For future reference, I'd left a comment saying that file.read() was possibly required)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.