Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File path in python

Tags:

python

json

file

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?

like image 599
PythonEnthusiast Avatar asked Apr 18 '26 16:04

PythonEnthusiast


2 Answers

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
like image 102
oleg Avatar answered Apr 21 '26 05:04

oleg


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')
like image 39
Rami Avatar answered Apr 21 '26 06:04

Rami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!