从层次结构文件夹顶部导入文件

时间:2018-02-21 21:57:19

标签: python

我无法导入变量" Base"来自层次结构顶部的文件(dataBase.py),如下所示: Structure and file dataBase.py

Store.py的内容:

from sqlalchemy import Column, String, Integer
from dataBase import Base


class Store(Base):
    __tablename__ = 'stores'

    id = Column(Integer, primary_key=True)
    name = Column(String(50))

    def __init__(self, name):
        self.name = name

line:"来自dataBase import Base"没有工作 - 我得到了:

File "Store/Store.py", line 2, in <module>
    from dataBase import Base
ImportError: No module named 'dataBase'

我尝试将所有文​​件夹添加到文件中:

__init__.py

但错误仍然像以前一样。

2 个答案:

答案 0 :(得分:0)

尝试改为尝试

# file dataBase
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class MY_OBJECT(Base):
  # your mappings here

# other file looking for base
import dataBase
base = dataBase.Base # access your base like this

适合我

答案 1 :(得分:0)

将文件所在目录的完整路径放入sys.path.insert。例如,如果dataBase的完整路径为C:/Users/Me/RentalApp/dataBase。你可以这样做:

import sys
sys.path.insert(0, 'C:/Users/Me/RentalApp')

from dataBase import Base