Search code examples
pythonpackage

calling a python module that reads a file


so my program import a utils that reads a file in the same directory as the utils. However, this utils function can be called from different files from different directory.


Project
|
|-module_1: 
     |__ init __.py
     | file.py <--- calls util.load_file() 
|module_2:
     | __ init __.py 
     | utils.py <---- load_file() path used 'file.txt' 
     | file.txt

what is this thing called ? I couldn't even search for it. tried package managment, expanding path ...etc


Solution

  • __file__ contains the path to the current file. Check it with print(__file__).

    pathlib from Pythons standard library can be used to construct an absolute path to the data file.

    import pathlib
    
    print(pathlib.Path(__file__))
    print(pathlib.Path(__file__).parent)
    print(pathlib.Path(__file__).parent / 'file.txt')
    

    You can now open your file like this:

    filepath = pathlib.Path(__file__).parent / 'file.txt'
    with open(filepath) as f:
        for line in f:
            print(line)