0

I'm a python beginner and I'm trying to read a function from one python file into another. However I am getting stuck with an import error. My directories are like this:

test folder

  • plot.py
  • setup folder containing (mapsetup.py, empty __init __.py file)

in mapsetup.py I have the following code:

def read_files (project_name):   
  extent_dir =(os.path.join (dir['extents_dir'],project_name, 'extent_'  + project_name + '.shp') )

and then in plot.py I have this

project_name = str(input())

sys.path.append('/Users/Documents/python/test/setup')
from setup.mapsetup import read_files

but I keep getting this error:

ImportError: cannot import name 'read_files' from 'setup.mapsetup'

5
  • Is the test folder on your Python path? Usually this means that the test folder is either your current working directory, or you explicitly added it to the Python path through a different means (e.g. the env var PYTHONPATH) Commented Jun 30, 2022 at 14:02
  • I think if /setup is in the path then you don't want setup. in the import statement Commented Jun 30, 2022 at 14:03
  • @Anentropic Given that they put a __init__.py file in setup, I think its same to assume that they do want it to be a package. Commented Jun 30, 2022 at 14:03
  • 1
    yes, perhaps it should be sys.path.append('/Users/Documents/python/test') ? Commented Jun 30, 2022 at 14:05
  • @Brian the test folder should be my current working directory. I tried changing it to sys.path.append('/Users/Documents/python/test') but still same error comes up Commented Jun 30, 2022 at 14:20

1 Answer 1

1

Presumably there is a function called read_files (check spelling).

There is a double use of the setup in path. So remove one or the other.

like this:


# either
sys.path.append('/Users/Documents/python/test/setup')
from mapsetup import read_files    # <-- removed

# or this
sys.path.append('/Users/Documents/python/test')   # <-- removed
from setup.mapsetup import read_files

Note, it you are using an editor like vscode, the intellisense will usually pick all this up as you are typing, so you will know that you are in the right place. very helpful.

Sign up to request clarification or add additional context in comments.

1 Comment

thankyou, i am using vscode! I tried restarting VSCode and running this again and it worked

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.