'Can't import .py files within new Notebooks in Google Colab

I can't find a way to import a python library in Google Colab anymore. The exact same code works on previous Notebooks, in the exact same location. But not on new Notebooks, or if I duplicate an existing Notebook.

Mounting the Drive beforehand by clicking on the left panel doesn't make a difference

# Mount Google Drive
import os
import sys
from google.colab import drive
drive.mount('/content/drive', force_remount=True)

# Add path and verify the module is present
the_path = '/content/drive/MyDrive/MyProject/'
files = os.listdir(z_path)
if not ('the_module.py' in files):
  print('the_module is missing', 'Files are:')
  print("\n".join(files))
else:
  print('the_module is found')
  # Add the_path to sys.path
  sys.path.append(z_path) # or sys.path.insert(0,z_path)
  import the_module as the_module_loaded


Solution 1:[1]

I found a solution by using importlib.util, but it complicates things a bit:

import importlib.util
the_path = '/content/drive/MyDrive/MyProject/'
spec = importlib.util.spec_from_file_location("the_module", the_path+ "the_module.py")
the_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(the_module)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marotte