You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Colab目录使用及导入自定义data.py文件问题求助

Fixing Import Issues with data.py in Google Colab

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 Notebooks folder. Use this command (note the exact path—case and spacing matter):

    %cd /content/drive/MyDrive/Colab Notebooks
    

    (If you see an error, try replacing MyDrive with My 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:

    !ls
    

    You should see data.py listed 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 sys and append the correct path to it:

    import sys
    sys.path.append('/content/drive/MyDrive/Colab Notebooks')
    
  • Now you can import data just 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:49:23