【问题标题】:Read a file relative to a class successor's definition读取与类继任者定义相关的文件
【发布时间】:2018-01-10 09:01:18
【问题描述】:

假设我有一个接口类Base 打算被继承。我需要在Base 中定义一个静态方法,该方法将读取并打印一个文本文件旁边的后继定义。我的尝试如下。

示例结构:

.../module/
      __init__.py
      Base.py
      A/
          __init__.py
          A.py
          file.txt
      B/
          __init__.py
          B.py
          file.txt

Base.py:

import os.path

class Base:
    @staticmethod
    def print_file():
        file = os.path.join(os.path.dirname(__file__), 'file.txt')
        with open(file, 'r') as f:
            print(f.read())

A.py(B.py 相同):

from module.Base import Base

class A(Base):
    pass

当我导入A 类并调用A.print_file() 时,此代码尝试读取.../module/file.txt 而不是.../module/A/file.txt,因为__file__ 似乎是根据Base.py 而不是A.py 计算的。

有没有办法在静态方法中读取A/file.txtB/file.txt 而无需A.pyB.py 中的附加代码?

【问题讨论】:

  • 只是猜测:使用检查模块,例如:inspect.getframeinfo(inspect.currentframe()).filename
  • @jojo print-在调用A.print_file() 时,在静态方法的其余部分打印.../module/Base.py 之前,正是这一行。似乎一切都是根据基类计算的。不过,谢谢,我会研究检查模块。
  • __file__ 将引用调用它的 当前 文件(模块)。

标签: python


【解决方案1】:

来自docs

__file__ 是加载模块的文件的路径名,如果它是从文件加载的。某些类型的模块可能缺少 __file__ 属性,例如静态链接到解释器的 C 模块;对于从共享库动态加载的扩展模块,它是共享库文件的路径名。

因此,__file__ 指向 Base.py 是有意义的,因为这是模块 Base 最初加载的位置。

An appropriate choice here could be getfile from the inspect package:

inspect.getfile(object):返回定义对象的(文本或二进制)文件的名称。

import os
import inspect

class Base:       
    @classmethod          
    def print_file(cls):                                
        file = os.paht.join(
            os.path.dirname(inspect.getfile(cls)),
            'file.txt'
            )  
        with open(file, 'r') as f:
            print(f.read())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    相关资源
    最近更新 更多