Sending a file path from .py to another .py

Question:

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?

Asked By: null92

||

Answers:

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)
Answered By: Tom McLean

After .read()ing a file you’re dealing with 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.

Answered By: S.B
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.