0

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?

Hayden Eastwood
  • 928
  • 2
  • 10
  • 20
BulletRain
  • 92
  • 9
  • 1
    try your first code, but run it from inside the directory, not from the outside – Gal May 18 '20 at 09:43
  • It looks like this is an issue with the "current directory". You might find this post helpful: https://stackoverflow.com/questions/5137497/find-current-directory-and-files-directory – Tobias May 18 '20 at 09:46
  • try 'a/test.json' – Dejene T. May 18 '20 at 09:49

2 Answers2

1

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'
...
ShPavel
  • 962
  • 1
  • 10
  • 17
0

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

Srikeshram
  • 87
  • 1
  • 5