Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get filename of imported modules (Including default) in Python?

A little context: I'm trying to create a module that can safely copy itself and all other required files to another location.

Say I have two modules.

a.py:

import b
import os
import tkinter

print(str(__file__))
print(str(b.getfile()))

b.py:

def getfile:
    return __file__

When a.py will then output

C:/path/to/code/a.py
C:\path\to\code\b.py

Question: How, if at all, can i get the path of a different imported module (like "os.py"), or any module without this getfile() function?

like image 955
PurpleSkyHoliday Avatar asked Sep 05 '25 03:09

PurpleSkyHoliday


1 Answers

You can access via

module_name.__file__

as in

import os
module_file_path = os.__file__

As pointed out in the comments, this won't work for some built-in modules like sys that come from the interpreter's core.

like image 70
Julien Avatar answered Sep 07 '25 20:09

Julien