Python file path

I am trying to download a 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 main.py file is stored outside folder1 . All this is stored in the project folder.

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

+4
source share
3 answers

I prefer to specify patterns starting from the 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 eliminates the need to worry about working directory changes. And also it allows you to run a script from any directory using the full path.

 python script/inner/script.py 

or

 python script.py 
+6
source

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

Sort of:

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

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

0
source

All Articles