无法在 Google Colab 中的新笔记本中导入.py文件



我再也找不到在Google Colab中导入python库的方法了。完全相同的代码适用于以前的笔记本,位于完全相同的位置。但不是在新的笔记本上,或者如果我复制了现有的笔记本。

点击左侧面板预先安装驱动器不会对产生影响

# 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

我使用importlib.util找到了一个解决方案,但它使事情有点复杂:

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)

最新更新