在堆栈中上一级获取函数的__file__
问题内容:
我发现我经常使用这种模式:
os.path.join(os.path.dirname(__file__), file_path)
因此,我决定将一个函数放入一个包含许多此类小实用程序的文件中:
def filepath_in_cwd(file_path):
return os.path.join(os.path.dirname(__file__), file_path)
事情是,__file__
返回 当前 文件,因此返回 当前 文件夹,而我已经错过了重点。我可以做这个丑陋的hack(或者只是继续写模式):
def filepath_in_cwd(py_file_name, file_path):
return os.path.join(os.path.dirname(py_file_name), file_path)
然后对其的调用将如下所示:
filepath_in_cwd(__file__, "my_file.txt")
但是如果我有办法__file__
在堆栈中上一层的话,我会更喜欢它。有什么办法吗?
问题答案: