Get the __file__ of the function one level up in t

2019-02-16 19:51发布

I've found that I'm using this pattern a lot :

os.path.join(os.path.dirname(__file__), file_path)

so I've decided to put in a function in a file that has many such small utilities:

def filepath_in_cwd(file_path): 
    return os.path.join(os.path.dirname(__file__), file_path)

The thing is, __file__ returns the current file and therefore the current folder, and I've missed the whole point. I could do this ugly hack (or just keep writing the pattern as is):

def filepath_in_cwd(py_file_name, file_path): 
    return os.path.join(os.path.dirname(py_file_name), file_path)

and then the call to it will look like this:

filepath_in_cwd(__file__, "my_file.txt")

but I'd prefer it if I had a way of getting the __file__ of the function that's one level up in the stack. Is there any way of doing this?

1条回答
男人必须洒脱
2楼-- · 2019-02-16 20:28

This should do it:

inspect.getfile(sys._getframe(1))

sys._getframe(1) gets the caller frame, inspect.getfile(...) retrieves the filename.

查看更多
登录 后发表回答