2

I wrote a module module.py that I import in various scripts. The module has a function that needs the file path of the script main.py that it was imported by and do something with it. How do I get this file path?

module.py

def main_file_path():
    print(way_to_acces_main_file_path)

is imported in

main.py

import module
module.main_file_path()

Running main.py should print the file path of main.py

3
  • Why not just pass in a path into main_file_path? This will also make it more reusable and generalized. Commented Jul 10, 2022 at 19:35
  • Because the real function in module.py always needs the file path of the script that imports it, and this function already has a few parameters. I think adding the file path as parameter will complicate the function. I am looking for something like file that I can call in the module. Commented Jul 10, 2022 at 19:40
  • This is an odd request. Are you sure there isn't a better way to do what you are trying to do? Commented Jul 10, 2022 at 20:46

2 Answers 2

2

The system argv always has the program name as the first element. This should work most of the time:

import sys
import os

path = os.path.abspath(sys.argv[0])
print(path)
Sign up to request clarification or add additional context in comments.

1 Comment

This works perfectly for what I intended. I wasn't aware that sys.argv[0] also gives the script name that is being executed when called inside a module. Thanks!
0

You can use the os module to get the path of a file:

# file_locator.py

import os


def get_file_location(filename):
    return os.path.abspath(filename)


if __name__ == '__main__':
    pass

# main.py

from file_locator import get_file_location

fileA = get_file_location(filename)


2 Comments

This would work if I only import module.py in main.py, but I use it in other scripts and want it to be flexible in regards to which script it is imported by.
I updated the code. Does this offer the flexibility you are trying to achieve?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.