Reputation: 92
I am having a silly problem with reading a file in python.
I have a folder 'a' that contains my test.py and file test.json for reading.
My test.py looks like this:
config_path = 'test.json'
with open(config_path) as config_buffer:
config = json.loads(config_buffer.read())
When I go outside the directory structure of folder 'a' and I run the command:
python a\test.py
And the console returns this error:
FileNotFoundError: No such file or directory: 'test.json'
I try using the absolute file path using pathlib:
config_path = Path('end2end.json').absolute()
with open(config_path) as config_buffer:
config = json.loads(config_buffer.read())
But it still returns this error to me:
FileNotFoundError: No such file or directory: 'D:\\test.json'
Can anyone help me to get exactly the right directory file?
Upvotes: 0
Views: 1527
Reputation: 973
If you want to call your python script from any folder and let it access its local files without specifying paths, you can change the directory in the begining:
import os
os.chdir(os.path.dirname(os.path.realpath(__file__)))
config_path = 'test.json'
...
Upvotes: 1
Reputation: 97
The Problem is that you should place the test.json
file in the current working directory.
i.e)For Example, The python file is located in C:\users\Desktop\Code\test.py
then you should copy the file into C:\users\Desktop\Code\
(OR)
You should give the path of the file in with open($PATH TO JSON FILE) as config_buffer
Upvotes: 0