Google Colab目录使用及导入自定义data.py文件问题求助
I get it—this confusion is super common with Colab's file system. The problem boils down to this: when you start a Colab notebook, its default working directory is /content, not the Colab Notebooks folder on your Google Drive. Even though your notebook is stored there, Colab doesn't automatically point to that directory unless you explicitly tell it to. Here's how to fix it:
Option 1: Mount Drive and Switch to Your Notebook Directory
This is the most straightforward approach.
Mount your Google Drive to Colab. Run this code cell and follow the authentication prompts to link your account:
from google.colab import drive drive.mount('/content/drive')Change your working directory to the
Colab Notebooksfolder. Use this command (note the exact path—case and spacing matter):%cd /content/drive/MyDrive/Colab Notebooks(If you see an error, try replacing
MyDrivewithMy Drive(with a space) in case your Drive uses the older naming convention.)Verify the file exists to be sure. Run this to list all files in the directory:
!lsYou should see
data.pylisted here.Now you can import your module normally:
import data
Option 2: Add the Drive Folder to Python's Path (Without Changing Directories)
If you don't want to switch your working directory, you can add the Colab Notebooks path to Python's system path so it knows where to look for data.py:
First, mount your Drive as before:
from google.colab import drive drive.mount('/content/drive')Import
sysand append the correct path to it:import sys sys.path.append('/content/drive/MyDrive/Colab Notebooks')Now you can import
datajust like you would locally:import data
A quick note: Double-check that data.py is indeed in the Colab Notebooks folder (not a subfolder) and that you haven't misspelled the filename—case matters in Linux-based systems like Colab's.
内容的提问来源于stack exchange,提问作者Danf

