10

I'm trying to load the json file but it gives me an error saying No such file or directory:

with open ('folder1/sub1/sub2/sub2/sub3/file.json') as f:
    data = json.load(f)
print data

The above file main.py is kept outside the folder1. All of this is kept under project folder.

So, the directory structure is Project/folder1/sub1/sub2/sub2/sub3/file.json Where am I going wrong?

3
  • Are you using abs path? It is 'folder1/...' but not '/folder1/...' ? And what's your current dir where you execute the main.py Commented Sep 23, 2013 at 7:56
  • I omitted the initial slash, but it didnt worked. My main.py file is kept under project folder Commented Sep 23, 2013 at 7:58
  • what's your current dir where you execute the main.py, If it not under the Project, the real path of f if your_current_dir + '/folder1/...' but not Project/folder1/sub1/sub2/sub2/sub3/file.json Commented Sep 23, 2013 at 8:01

3 Answers 3

18

I prefer to point pathes starting from file directory

import os
script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, 'relative/path/to/file.json')
with open(file_path, 'r') as fi:
    pass

this allows not to care about working directory changes. And also this allows to run script from any directory using it's full path.

python script/inner/script.py

or

python script.py
Sign up to request clarification or add additional context in comments.

Comments

2

I would use os.path.join method to form the complete path starting from the current directory.

Something like:

json_filepath = os.path.join('.', 'folder1', 'sub1', 'sub2', 'sub3', 'file.json')

Comments

0

As always, an initial slash indicates that the path starts from the root. Omit the initial slash to indicate that it is a relative path.

1 Comment

Which "Correct" path?

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.