【问题标题】:How to import a py module from a sub-dir (which's name starts with digits) of parent directory如何从父目录的子目录(名称以数字开头)导入 py 模块
【发布时间】:2021-11-22 09:45:18
【问题描述】:

由于问题的标题可能令人困惑,我想澄清一下我的问题

想象以下目录结构:

  • 父目录
    • 01_sub-dir
      • file01.py
    • 02_sub-dir
      • file02.py

在 file02.py 中,我想通过使用相对导入来导入位于 file01.py 中的类。

我尝试从 01_subdir 导入类“my_class”,如下所示: from ..01_subdir.file01 import my_class

我不断收到以下错误:

SyntaxError: invalid decimal literal

目录结构无法更改。

很遗憾我不能分享源代码。

【问题讨论】:

  • 01_sub-dir 根据 Python 语法规范不是合法的 identifier,因此您无法将其用作导入语句的一部分。

标签: python python-3.x import


【解决方案1】:

项目中的所有路径都是相对于根目录的。 尝试简单:

from 01_subdir.file01 import my_class

【讨论】:

  • 但你应该从根目录运行 file02 作为 "python3 02_subdir/file02.py"
猜你喜欢
  • 2017-11-30
  • 2015-07-23
  • 2019-11-10
  • 1970-01-01
  • 2021-08-24
  • 1970-01-01
  • 1970-01-01
  • 2019-05-31
  • 1970-01-01
相关资源
最近更新 更多