felipez
felipez

Reputation: 1212

error importing module and loading files

I have a package structure like:

my_pkg:

Inside the foo.py module I have something like:

import json
def loadFromJSON(fileName):
    with open(fileName,'r') as f:
         xs = json.load(f)
    return xs

bar  = loadFromJSON('bar.json')

The problem is when I try to import things from my_pkg:

python
>>> from my_pkg import *
>>> ..../my_pkg/proj2/foo.py in loadFromJSON(fileName)
>>> --->  with open(fileName,'r') as f:
>>>           xs = json.load(f)
>>>       return xs
>>> FileNotFoundError: [Errno 2] No such file or directory: 'bar.json'

but if I do:

>>> cwd
>>> '.../my_pkg/proj2/`
>>> from foo import bar
>>> bar 

It works. Could someone please explain me what's going on here?

Upvotes: 0

Views: 171

Answers (2)

chaos
chaos

Reputation: 133

just like you said, the point is 'cwd': you can add your 'cwd' and then import module:

import sys
sys.path.append('your cwd here')

then do:

from foo import bar

Upvotes: 0

toti08
toti08

Reputation: 2454

(For completeness I transfer the comment to an answer)

I think you should use the full path for you "bar.json" file.

Upvotes: 1

Related Questions