Home > Software design >  Sending a file path from .py to another .py
Sending a file path from .py to another .py

Time:10-20

I'm trying to call a foo.py passing a filePath to bar.py

foo.py

for path in Path('./csvs').rglob('*.csv'):
    exec(open('bar.py').read())
    exec(open('bar2.py').read())
    exec(open('bar3.py').read())

bar.py

df = pd.read_csv(path, usecols=cols)
#rest of code

Is it possible?

CodePudding user response:

After .read()ing a file you can treat it as a string. So you can .replace() a placeholder.

file1.py:

exec(open("file2.py").read().replace("*place_holder*", "10"))

file2.py:

def fn():
    print("My number is *place_holder*")
fn()

But be careful about what you choose as the placeholder. .replace() will replace all the occurrences.

Of course for more complex replacing you can use regex. It can restrict the search better and safer.

CodePudding user response:

I dont know the exact format of your bar.py, but you can try:

for filePath in Path('./csvs').rglob('*.csv'):
    for i in range(1, 4):
        with open(f`bar{i}.py`) as f;
            bar_py_str = f.read()

        bar_py_str = bar_py_str.replace(
            'df = pd.read_csv(filePath, usecols=cols)',
            f'df = pd.read_csv({str(filePath.resolve()}, usecols=cols)'
        )

        exec(bar_py_str)
  • Related