提问人:Leo 提问时间:2/13/2021 最后编辑:Leo 更新时间:3/11/2022 访问量:4229
查找 python_notebook.ipynb 的路径时与 Google Colab 一起运行它
Find path of python_notebook.ipynb when running it with Google Colab
问:
我想找到存储我的 CODE 文件的 cwd。
对于木星实验室,我会做:
import os
cwd= os.getcwd()
print (cwd)
OUT:
'C:...\\Jupiter_lab_notebooks\\CODE'
但是,如果我将文件夹复制到我的GoogleDrive,并在GOOGLE COLAB中运行笔记本,我会得到:
import os
cwd= os.getcwd()
print (cwd)
OUT:
/content
无论我的笔记本存放在哪里。 如何找到我的 .ipynb 文件夹存储的实际路径?
#EDIT
我正在寻找的是 python 代码,无论它存储在驱动器的哪个位置,它都会返回 COLAB 笔记本的位置。这样我就可以从那里导航到子文件夹。
答:
Google colab 允许您将笔记本保存到 Google Drive,当您创建新笔记本时,您可以单击文件菜单中的“在驱动器中定位”以访问此位置。
请注意,您可以将驱动器挂载到 colab 实例,这意味着您可以将 google drive 作为 colab 实例中的子文件夹访问,但是,如果您要在本地 google drive 文件夹(由 google drive 应用程序创建)中查找物理位置,那么这应该类似于这个位置(在 Mac 上)。
/Volumes/GoogleDrive/My Drive/Colab Notebooks/
但是,如果您已将Google驱动器安装在colab上,并且正在通过google colab查找笔记本电脑的保存位置,请尝试以下操作 -
path = '/content/drive/MyDrive/Colab Notebooks'
评论
由于GoogleDrive是您当前的工作目录,因此您需要先从colab挂载它:
from google.colab import drive
drive.mount('/content/drive/')
然后,您需要将目录更改为存储的位置:.ipynb
import os
os.chdir('/content/drive/MyDrive/path/to/your/folder')
最后,如果你这样做
import os
cwd= os.getcwd()
print (cwd)
你会得到类似你的存储位置的东西。/content/drive/MyDrive/path/to/your/folder
.ipynb
当你这样做时
import subprocess
subprocess.check_output(['ls'])
您将看到您的笔记本文件列在那里。
如果要导航到子文件夹,只需使用 .os.chdir()
这个问题已经困扰了我一段时间,如果笔记本被单独找到,这段代码应该设置工作目录,仅限于 Colab 系统和挂载的驱动器,这可以在 Colab 上运行:
import requests
import urllib.parse
import google.colab
import os
google.colab.drive.mount('/content/drive')
def locate_nb(set_singular=True):
found_files = []
paths = ['/']
nb_address = 'http://172.28.0.2:9000/api/sessions'
response = requests.get(nb_address).json()
name = urllib.parse.unquote(response[0]['name'])
dir_candidates = []
for path in paths:
for dirpath, subdirs, files in os.walk(path):
for file in files:
if file == name:
found_files.append(os.path.join(dirpath, file))
found_files = list(set(found_files))
if len(found_files) == 1:
nb_dir = os.path.dirname(found_files[0])
dir_candidates.append(nb_dir)
if set_singular:
print('Singular location found, setting directory:')
os.chdir(dir_candidates[0])
elif not found_files:
print('Notebook file name not found.')
elif len(found_files) > 1:
print('Multiple matches found, returning list of possible locations.')
dir_candidates = [os.path.dirname(f) for f in found_files]
return dir_candidates
locate_nb()
print(os.getcwd())
评论