0

I have a problem. I want to call inside my Jupyter Notebook a Python File. I looked at How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook? but unfortunately %run -i 'file.py' and !python file.py does not work, because my file is not in the same folder as the Jupyter Notebook file.

So how could I call a Python file from a different folder? Jupyter Notebook

from pathlib import *
# I am using pathlib, because of the whitespace in OneDrive
p = Path('C://Users//user//OneDrive - user//folder//file.py')
# %run -i ''C://Users//user//OneDrive - user//folder//file.py'
!python p
[OUT] python: can't open file 'C:\Users\user\Documents\p': [Errno 2] No such file or directory

file.py

def main():
    print("Hello")
    return "test"

if __name__ == "__main__":
    main()

Test
  • 571
  • 13
  • 32

2 Answers2

1

chdir() changes the current working directory to the given path.

This should do your work:

import os
filepath = r'C:\Users\user\OneDrive - user\folder' 
os.chdir(filepath)
%run file.py
SM1312
  • 516
  • 4
  • 13
0

Assuming your file is in a sub-folder ./playground/test folder, then you could do this:

file_name = ".\\playground\\test folder\\hello_world.py"

%run "$file_name"

The trick is to use quotation marks around the file name (if path contains spaces) when using %run.

The same applies if you use !python:

file_name = ".\\playground\\test folder\\hello_world.py"

!python "$file_name"
Thomas
  • 8,357
  • 15
  • 45
  • 81