Menfis Menfis
Menfis Menfis

Reputation: 63

Import a file from another directory

I have a file call entryPoint.py :

from .commonLib.deviceLib import *

And I have a file called deviceLib.py :

import math
import sys
import logging
import requests
import this

class DeviceLib(object):
    def __init__(self, connectionDb):
        self.__db = connectionDb

The tree is like this :

/test
    entryPoint.py
/commonLib
    __init__.py
    deviceLib.py

When I execute python entryPoint.py I get the error : Attempted relative import in non-package. Please help me.

Upvotes: 3

Views: 21645

Answers (3)

ewalel
ewalel

Reputation: 2086

use sys.path.append to append the directory where your python file (module is). E.g if your entryPoint.py is inside address directory

import sys
sys.path.append('/path/to/your/module/address/')
import entryPoint

Upvotes: 14

Khalil Al Hooti
Khalil Al Hooti

Reputation: 4496

There should be __init__.py in the folder both /test and /commonLib reside.

then just do

from commonLib import deviceLib

For example

sound
|-- effects
|   |-- echo.py
|   |-- __init__.py
|   |-- reverse.py
|   `-- surround.py
|-- filters
|   |-- equalizer.py
|   |-- __init__.py
|   |-- karaoke.py
|   `-- vocoder.py
|-- formats
|   |-- aiffread.py
|   |-- aiffwrite.py
|   |-- auread.py
|   |-- auwrite.py
|   |-- __init__.py
|   |-- wavread.py
|   `-- wavwrite.py
`-- __init__.py

lets assume you are right now opened wavread.py in format subdirecory, you can import karaoke.py from filters by just

from filters import karaoke

More information Here, https://www.python-course.eu/python3_packages.php

Upvotes: 1

amirhosein majidi
amirhosein majidi

Reputation: 149

To import a file from another directory you can use this code :

import sys
sys.path.insert(0, 'folder destination')
import file

As you can see here we included the path so python will look for the file in that path as well.

Upvotes: 0

Related Questions