How to import a python .py file in Jupyter Notebook

Viewed 11905

I have a Jupyter Notebook and I would like to use some credentials I have put into a config.py file. This file is in the same folder as the Jupyter Notebook.

I use the line

import config

The problem is Jupyter replies with this message:

ModuleNotFoundError: No module named 'config.py'; 'config' is not a package

Thank you for your help

3 Answers

You may need to try

from config import <the_function_you_want_to_use>

This should work with global variables too depending on how you stored your credentials in config. If you are importing the module from a different folder you could make the folder into a package by creating an empty .py file in the folder called:

__init__.py

Then storing a copy of the .py file you want to use as a module there and calling it. I'm new at this so I hope this helps.

The import statement is used to bring in external libraries to use in your program. I think you may be looking to read the file, so provided it is in the same folder path as your notebook you can use this:

file = open("config.py", "r")

You can then set the contents in the file to a variable and print it out for example using:

fileContents = file.read()
print(fileContents)

You may wish to use a csv format and add some sort of encryption if this is a stored password for example.

After some research, I have found a way to solve my need using Dotenv Python Package: pypi.org/project/python-dotenv

What needs to be done? Insert the following lines:

!pip install python-dotenv

# Credentials file
%load_ext dotenv
%dotenv
import os

Then place a hidden file named .env where the credentials are places. In my case it looks like this:

CLIENT_ID = "XXXX"
CLIENT_SECRET = "YYYY"

Then, in your notebook file, whenever you need to load the credentials use:

CLIENT_ID = os.getenv("CLIENT_ID")
CLIENT_SECRET = os.getenv("CLIENT_SECRET")

And you are good to go!

Credit to http://veekaybee.github.io/2020/02/25/secrets/ for the solution

Related