Dav*_*d 8 9 python path getcwd jupyter-notebook google-colaboratory
我想找到存储我的 CODE 文件的 cwd。
有了木星实验室我会这样做:
import os
cwd= os.getcwd()
print (cwd)
OUT:
'C:...\\Jupiter_lab_notebooks\\CODE'
Run Code Online (Sandbox Code Playgroud)
但是,如果我将文件夹复制到我的 GoogleDrive,并在 GOOGLE COLAB 中运行笔记本,我会得到:
import os
cwd= os.getcwd()
print (cwd)
OUT:
/content
Run Code Online (Sandbox Code Playgroud)
无论我的笔记本存放在哪里。如何找到 .ipynb 文件夹存储的实际路径?
#编辑
我正在寻找的是 python 代码,它将返回 COLAB 笔记本的位置,无论它存储在驱动器中的哪个位置。这样我就可以从那里导航到子文件夹。
小智 4
这个问题已经困扰我一段时间了,如果笔记本被发现异常,这段代码应该设置工作目录,仅限于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())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4741 次 |
| 最近记录: |