【问题标题】:Creating a submodule that relies on a properties file创建依赖于属性文件的子模块
【发布时间】:2018-11-09 19:45:37
【问题描述】:

我有以下结构

main.py
module/
    properties.yaml
    file.py

file.py相关代码:

def read_properties():
    with open('properties.yaml') as file:
        properties = yaml.load(file)

main.py相关代码:

from module import file
file.read_properties()

在 main.py 中调用 read_properties() 时,出现以下错误:FileNotFoundError: [Errno 2] No such file or directory: 'properties.yaml'

推荐的方式是允许我的模块在导入时访问属性文件吗?

【问题讨论】:

    标签: python import python-import python-3.7


    【解决方案1】:

    提供properties.yaml的绝对路径:

    with open('/Users/You/Some/Path/properties.yaml') as file:
    

    【讨论】:

      【解决方案2】:

      正如 JacobIRR 在他的回答中所说,最好使用文件的绝对路径。我使用 os 模块根据当前工作目录构造绝对路径。因此,对于您的代码,它将类似于:

      import os
      working_directory = os.path.dirname(__file__)
      properties_file = os.path.join(working_directory, 'module', 'properties.yaml')
      

      【讨论】:

        【解决方案3】:

        基于@JacobIRR 和@BigGerman 的回答

        我最终使用了 pathlib 而不是 os,但逻辑是一样的。 以下是 pathlib 的语法供感兴趣的人参考:

        在文件.py中:

        from pathlib import Path
        properties_file = Path(__file__).resolve().parent/"properties.yaml"
        with open(properties_file) as file:
            properties = yaml.load(file)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-11-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-05-07
          • 1970-01-01
          相关资源
          最近更新 更多