RemcoW RemcoW - 5 months ago 9
Python Question

Getting a class's filepath starting from the current working directory

I am trying to print the path to a file. I want the full path from the current working directory to the file.

I am using the

inspect
module to find the path to my file. However this will give me the full path which is not what I'm looking for.

import inspect

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


Now for the filename itself I can use
os.path.basename
. But this will give me just the filename which is also not what I want.

import inspect
import os

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


It would be relatively easy to use the
path
in combination with
os.getcwd()
to get the path I am looking for. This will give me the result I am looking for.

import inspect
import os


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


I am wondering if there is a better/easier way to do this?

Answer

I think os.path.relpath() does what you want it to.

Example:

import os, inspect

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


foo = Foo()
print(foo.path)
Comments