【问题标题】:Importing python files in another python file [duplicate]在另一个python文件中导入python文件[重复]
【发布时间】:2020-08-18 14:19:17
【问题描述】:

我有一个这种文件结构的文件夹:

Desktop
    tech_comp
       googledash.csv
       viz.py
       sql_load.py

       company_AL
           __init__.py
           functionloads.py
           decisionplans.py
           niches.py
           actions.py

我正在与VScode 合作,如上所述:C:\Users\username\Desktop\tech_comp\company_AL

我在decisionplans.py 中写了一堆list,现在我正在尝试将它加载到我正在使用的actions.py 中。这就是我所做的。

from company_AL import decisionplans

它没有在compiler 中显示errors,但是当我运行时,我得到以下信息。

ModuleNotFoundError: No module named 'company_AL'

我不打算在线发布,因为这是一个私人项目,请问我该如何处理?

提前致谢

【问题讨论】:

  • 您的启动地点在哪里?由于它是通过相对路径导入的(除非在导入路径中找到),因此在导入时需要考虑这一点。
  • 什么意思?不清楚
  • 当您运行脚本时,您从哪个文件夹执行?如果你打开一个终端,然后导航到一个文件夹,运行python <some script.py>,你在哪个文件夹中? :) (VScode 使用“工作目录”或类似的相同原理)

标签: python python-3.x class oop python-import


【解决方案1】:

您有很多解决方案可以解决您的问题:

1。将 compagn_AL 文件夹添加到您的 PYTHON_PATH

这取决于您的操作系统,但有些教程比我解释得更好

2。更改脚本的 PATH

import sys
sys.path.append('../') # or "C:\Users\username\Desktop\tech_comp\"

然后

from compagny_AL import decisionplans

3。直接导入(不推荐)

你可以

import decisinplans

【讨论】:

    【解决方案2】:

    我认为你只需要做import decisionplansfrom .company_AL import decisionplans,因为你已经在company_AL 中了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-01
      • 2018-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多