1

I have a problem. I created a script that uses a few functions, but now I have moved those functions in a folder named: include. The file is called: mylib.py, but when I use the following code:

import sys
sys.path.insert(0, 'include/')

import mylib

It gives an error: No module named 'mylib'. The main code is in the windows directory: Desktop/Python/ and the include file in: Desktop/Python/include/.

What am I doing wrong?

A. Vreeswijk
  • 822
  • 1
  • 19
  • 57
  • Duplicate: https://stackoverflow.com/questions/1260792/import-a-file-from-a-subdirectory – Tomerikoo Nov 10 '20 at 10:39
  • I have changed the import to: `from include import mylib`, but that still returns me the error: `cannot import name 'mylib' from 'include' (unknown location)`. I have done what the duplicate said, but no luck yet – A. Vreeswijk Nov 10 '20 at 10:44

2 Answers2

3

add an empty file __init__.py to the include folder to make it a package.

then import from it with:

from include import mylib
dzang
  • 2,160
  • 2
  • 12
  • 21
  • 1
    `cannot import name 'mylib' from 'include' (unknown location)` – A. Vreeswijk Nov 10 '20 at 10:31
  • can you add the folder structure of your project, where is your script and where you are calling the script from? This assumes that your script is on the same level of the `include` folder and that you are running it with `python script.py` If this is not the case you can let the interpreter know where the include folder is by adding its location to the path. So if the full path is `/home/user/docs/include` then in the script add `sys.path.append('/home/user/docs')` – dzang Nov 10 '20 at 10:53
  • it's also possible that the problem is the name of the files you choose. try to rename them , eg to src/mylib.py instead of include/mylib.py or check if there is any typo and the file is actually called mylib.py – dzang Nov 10 '20 at 11:01
0

Replace the second line with this one:

sys.path.insert(0, '/Desktop/Python/include')

Lixas
  • 6,938
  • 2
  • 25
  • 42
Pavlos
  • 906
  • 1
  • 11
  • 29
  • 1
    @A.Vreeswijk you need the full path... On Windows it should be something like `C:/Users/user/Desktop/...` – Tomerikoo Nov 10 '20 at 10:36
  • 1
    That still returns me the same error? My path is correct now! – A. Vreeswijk Nov 10 '20 at 10:37
  • ok @A.Vreeswijk you need to check your python version, if you are using conda env or not, if you are not try anaconda and your code should work – Pavlos Nov 10 '20 at 10:40