Issue
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()
Solution
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
Answered By - SM1312
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.