PurpleSkyHoliday
PurpleSkyHoliday

Reputation: 109

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?

Upvotes: 4

Views: 3933

Answers (2)

Julien
Julien

Reputation: 5759

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.

Upvotes: 6

viraptor
viraptor

Reputation: 34205

You can use:

import os
print(os.__file__)

Upvotes: 1

Related Questions