【问题标题】:Getting a class's filepath starting from the current working directory [duplicate]从当前工作目录开始获取类的文件路径[重复]
【发布时间】:2016-10-17 16:06:24
【问题描述】:

我正在尝试打印文件的路径。我想要从当前工作目录到文件的完整路径。

我正在使用inspect 模块来查找我的文件的路径。但是,这会给我完整的路径,这不是我想要的。

import inspect

class Foo:
    def __init__(self):
        print(inspect.getfile(self.__class__))

现在对于文件名本身,我可以使用os.path.basename。但这只会给我文件名,这也不是我想要的。

import inspect
import os

class Foo:
    def __init__(self):
        path = inspect.getfile(self.__class__)
        filename = os.path.basename(path)
        print(path)
        print(filename)

pathos.getcwd() 结合使用会相对容易获得我正在寻找的路径。这会给我我正在寻找的结果。

import inspect
import os


class Foo:
    def __init__(self):
        path = inspect.getfile(self.__class__)
        cwd = os.getcwd()
        print(path[len(cwd):])

我想知道是否有更好/更简单的方法来做到这一点?

【问题讨论】:

  • 你考虑过os.path.relpath吗?
  • @jonrsharpe 不,我没有。这确实更好,谢谢。

标签: python python-3.x filepath


【解决方案1】:

我认为os.path.relpath() 可以满足您的要求。

例子:

import os, inspect

class Foo():
    def __init__(self):
        self.path = os.path.relpath(inspect.getfile(self.__class__))


foo = Foo()
print(foo.path)

【讨论】:

    猜你喜欢
    • 2020-03-19
    • 2019-01-27
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多