Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent of Matlab addpath

Does python have an equivalent to Matlab's addpath? I know about sys.path.append, but that only seems to work for python files/modules, not for general files.

Suppose I have a file config.txt in C:\Data and the current working directory is something else, say D:\my_project.

I would like to have code similar to:

def foo():
    with open('config.txt') as f:
        print(f.read())

def main():
    addpath(r'C:\Data')
    foo()

Obviously I could pass the path to foo here, but that is very difficult in the actual use case.

like image 744
user2133814 Avatar asked Oct 15 '25 07:10

user2133814


2 Answers

You can't add multiple paths like you would in matlab.

You can use os.chdir to change directories, and access files and sub-directories from that directory:

import os

def foo():
    with open('config.txt') as f:
        print(f.read())

def main():
    os.chdir(r'C:\Data')
    foo()

To manage multiple directories, using a context manager that returns to the previous directory after the expiration of the context works:

import contextlib
import os

@contextlib.contextmanager
def working_directory(path):
    prev_cwd = os.getcwd()
    os.chdir(path)
    yield
    os.chdir(prev_cwd)

def foo():
    with open('config.txt') as f:
        print(f.read())

def main():
    with working_directory(r'C:\Data'):
        foo()
    # previous working directory
like image 197
Moses Koledoye Avatar answered Oct 16 '25 20:10

Moses Koledoye


No, it doesn't. Python doesn't work this way. Files are loaded from the current working directory or a specific, resolved path. There is no such thing as a set of pre-defined paths for loading arbitrary files.

Keeping data and program logic separate is an important concept in Python (and most other programming languages besides MATLAB). An key principle of python is "Explicit is better than implicit." Making sure the data file you want to load is defined explicitly is much safer, more reliable, and less error-prone.

So although others have shown how you can hack some workarounds, I would very, very strongly advise you to not use this approach. It is going to make maintaining your code much harder.

like image 43
TheBlackCat Avatar answered Oct 16 '25 21:10

TheBlackCat