【发布时间】: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)
将path 与os.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