如何获取Google Colab中运行的.ipynb文件的实际存储路径
Colab 环境获取当前运行 Notebook 实际存储路径方案
路径返回异常的原因
Colab 运行在隔离的临时虚拟机环境中,虚拟机默认的工作目录固定为/content,和你将.ipynb文件存储在Google Drive的具体挂载路径没有绑定关系,因此直接运行原生os.getcwd()永远只能返回临时工作区路径,无法获取文件的真实存储位置。
可通用复用的适配代码
不需要手动指定文件所在位置,代码可自动匹配当前运行的Notebook对应的存储路径,适配任意目录结构:
from google.colab import drive import os import re from IPython import get_ipython # 第一步:挂载Google Drive到Colab环境 drive.mount('/content/drive') def locate_notebook_dir(): # 获取当前内核会话的唯一标识UUID kernel_conn_file = get_ipython().config['IPKernelApp']['connection_file'] session_uuid = re.search(r'kernel-([\w-]+)\.json', kernel_conn_file).group(1) # 遍历Drive目录下所有Notebook文件,匹配当前会话对应的文件 drive_mount_root = '/content/drive/MyDrive' for root, _, files in os.walk(drive_mount_root): for file_name in files: if not file_name.endswith('.ipynb'): continue file_full_path = os.path.join(root, file_name) try: with open(file_full_path, 'r', encoding='utf-8') as f: file_content = f.read() # Notebook元数据中会嵌入运行时的会话UUID,匹配即可定位文件 if session_uuid in file_content: # 返回Notebook所在的目录路径,而非文件本身路径 return os.path.dirname(file_full_path) except Exception: continue return None # 调用获取当前Notebook的所在目录 notebook_work_dir = locate_notebook_dir() print(f"当前Notebook实际存储目录:{notebook_work_dir}") # 后续可直接基于该路径访问同目录下的子文件夹,例如: # sub_folder_path = os.path.join(notebook_work_dir, "你的子文件夹名称")
使用注意事项
- 代码默认遍历个人Google Drive的根目录定位文件,如果Notebook存储在共享硬盘下,只需将代码中的
drive_mount_root变量值替换为对应共享盘的挂载路径(形如/content/drive/Shareddrives/共享盘名称)即可正常识别。 - 如果你的Google Drive中存储的Notebook文件数量较多,首次运行定位代码的遍历耗时会稍长,匹配完成后返回的路径结果是准确的,不需要手动输入文件路径修正。
- 代码返回的是Notebook文件所在的绝对目录路径,后续拼接同目录下的子文件、子文件夹路径时,不会偏移到
/content临时工作目录,可直接对接原Jupyter Lab环境下的路径访问逻辑。
内容的提问来源于stack exchange,提问作者Leo
相关产品推荐
相关产品推荐

