2

This is my file tree:

run.py
foo/
    file.py
    foo.json

In file.py there is the following code:

import json

print(json.load(open('foo.json')))

In run.py there is the following code:

import foo.foo as foo

When running run.py I get the following error:

Traceback (most recent call last):
  File "run.py", line 1, in <module>
    import foo.foo as foo
  File "C:\Users\user\Desktop\foo\foo.py", line 3, in <module>
    print(json.load(open('foo.json')))
FileNotFoundError: [Errno 2] No such file or directory: 'foo.json'

How do I run run.py without getting that error and without run.py being in the same directory. Any help is appreciated!

vsp0
  • 67
  • 4

2 Answers2

2

Get the absolute path os.path.abspath(os.path.join(os.path.dirname(__file__), 'your file')

In your file put the path from the top of the project, should be /foo/foo.json

Capie
  • 976
  • 1
  • 8
  • 20
2

As @DeepSpace mentioned can you try setting foo.json to foo/foo.json? As the error indicates it is not able to find such file called 'foo.json` so it's likely to do with the file not being located.

You can also run it with an Absolute path (read here). Try getting the current working directory and setting the file_name as the argument.

Python 2 and 3

For the directory of the script being run:

import os
os.path.dirname(os.path.abspath(__file__))

If you mean the current working directory:

import os
os.path.abspath(os.getcwd())

Read more on this from the docs here

AzyCrw4282
  • 7,222
  • 5
  • 19
  • 35