Import a file from another directory

核能气质少年 提交于 2021-02-07 21:03:08

问题


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.


回答1:


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



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/52149113/import-a-file-from-another-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!