Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import py file in another directory in Jupyter notebook

My question is related to this. I am using Python 3.6 in Jupyter Notebook. My project directory is /user/project. In this directory I'm building a number of models and each has its own folder. However, there is a common functions.py file with functions that I want to use across all models. So I want to keep the functions.py file in /user/project but be able to call it from an .ipynb file in /user/project/model1, /user/project/model2, etc... How can I do this?

like image 386
Gaurav Bansal Avatar asked Mar 13 '18 19:03

Gaurav Bansal


People also ask

Can we import py file in Jupyter Notebook?

A module is simply a text file named with a . py suffix, whose contents consist of Python code. A module can be imported into an interactive console environment (e.g. a Jupyter notebook) or into another module.

How do I import a .py file into another folder?

The most Pythonic way to import a module from another folder is to place an empty file named __init__.py into that folder and use the relative path with the dot notation. For example, a module in the parent folder would be imported with from .. import module .

How do I import a function from another Python file to a Jupyter Notebook?

py file), or Jupyter Notebook. Remember the file that contains the function definitions and the file calling the functions must be in the same directory. To use the functions written in one file inside another file include the import line, from filename import function_name .


1 Answers

There is no simple way to import python files in another directory. This is unrelated to the jupyter notebook

Here are 3 solutions to your problem

  1. You can add the directory containing the file you want to import to your path and then import the file like this:
import sys   sys.path.insert(0, '/path/to/application/app/folder')  import file 
  1. You can create a local module by having an empty __init__.py file in the folder you want to import. There are some weird rules regarding the folder hierarchy that you have to take into consideration.

  2. You can create a module for the file you wish to import and install it globally.

like image 68
honeyspoon Avatar answered Sep 25 '22 23:09

honeyspoon