Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImportError: attempted relative import with no known parent package

Tags:

python

Can't seem to find a straightforward answer to this question. All I want to know is how to import the file I saved under my \scripts directory.

I added the path to sys.path...

import sys
sys.path.insert(0, "C:\\my_Stuff\\data_science\\scripts")

I added a __init__.py file under my \scripts directory, which is the same directory where my tree.py file is.

I run...

import tree as tr

...but am still getting the error.

like image 272
Kurt_Brummert Avatar asked Sep 18 '17 02:09

Kurt_Brummert


People also ask

How do you fix ModuleNotFoundError and ImportError?

Python's ImportError ( ModuleNotFoundError ) indicates that you tried to import a module that Python doesn't find. It can usually be eliminated by adding a file named __init__.py to the directory and then adding this directory to $PYTHONPATH .

What is relative import in Python?

A relative import specifies the resource to be imported relative to the current location—that is, the location where the import statement is. There are two types of relative imports: implicit and explicit. Implicit relative imports have been deprecated in Python 3, so I won't be covering them here.


1 Answers

My answer is probably late but the following is working for me.

Let's say i have "my_file.py" in the directory "folder":

import sys
sys.path.append('path\\to\\folder')

from my_file import ...

Hope this can help!

like image 62
Baptiste Pouthier Avatar answered Oct 12 '22 16:10

Baptiste Pouthier