Python Forum
where module is loaded from
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
where module is loaded from
#1
i have a module with some code inside that needs to know what exact file path it was loaded from. another file in the same directory will have some data a feature needs to access.

the use will be to take this path and split the directory path and the base file name, join the directory path with a different base file name, open this different file path, open this different file path, read this different file path, and act on the data contents.

how can the code inside this module find the path of the file it was loaded from, or at least its directory path, preferably without knowing the module name in advance. is there a place to get this information?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
(Jul-25-2023, 10:03 PM)Skaperen Wrote: have a module with some code inside that needs to know what exact file path it was loaded from.
Use
__file__
or almost equivalently
__spec__.origin
In order to reliably aggregate data files to a Python package, it is better to use importlib.resources. Also read setuptools' data files support.
Skaperen likes this post
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020