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?
__file__ is a variable that contains the path to the module that is currently being imported. Python creates a __file__ variable for itself when it is about to import a module. The updating and maintaining of this variable is the responsibility of the import system.
dirname() method in Python is used to get the directory name from the specified path.
os.path. realpath(path, *, strict=False) Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path (if they are supported by the operating system). If a path doesn't exist or a symlink loop is encountered, and strict is True , OSError is raised.
To return the directory you are currently in, we use the OS module to interact with the operating system. Under the OS module, we use the os. getcwd() method to return the path of the current directory.
This should do it:
inspect.getfile(sys._getframe(1))
sys._getframe(1)
gets the caller frame, inspect.getfile(...)
retrieves the filename.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With