Skip to main content
 首页 » 编程设计

python之读取与类继承者定义相关的文件

2025年01月19日10birdshome

假设我有一个接口(interface)类 Base打算继承。我需要在 Base 中定义一个静态方法这将读取并打印紧接着继任者定义的文本文件。我的尝试如下。

示例结构:

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

基础.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.txt和 B/file.txt在 A.py 中没有附加代码的静态方法中和 B.py ?

请您参考如下方法:

来自docs :

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute may be missing for certain types of modules, such as C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

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

此处的合适选择可能是 getfile来自检查包:

inspect.getfile(object): Return the name of the (text or binary) file in which an object was defined.

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())