将本地文件导入 google colab

import local file to google colab

我不明白 colab 是如何处理目录的,我创建了一个笔记本,colab 把它放在 /Google Drive/Colab 笔记本中。

现在我需要导入一个文件 (data.py),其中包含大量我需要的函数。直觉告诉我将文件放在同一个目录中并使用以下命令导入它:

导入数据

但显然不是这样...

我也尝试将目录添加到路径集中,但我指定的目录不正确..

有人可以帮忙吗?

提前致谢!

Colab 笔记本存储在 Google 驱动器上。但是在另一个虚拟机上是运行。因此,您也需要将 data.py 复制到那里。执行此操作以通过 Colab 上传 data.py。

from google.colab import files
files.upload()
# choose the file on your computer to upload it then
import data

从系统上传本地文件到协作storage/directory。

from google.colab import files
def getLocalFiles():
    _files = files.upload()
    if len(_files) >0:
       for k,v in _files.items():
         open(k,'wb').write(v)
getLocalFiles()

所以,这就是我最终解决这个问题的方法。然而,我必须指出,在我的例子中,我不得不使用几个一直在变化的文件和专有模块。

我找到的最佳解决方案是使用 FUSE 包装器 "link" colab 到我的 google 帐户。我使用了这个特殊的工具:

https://github.com/astrada/google-drive-ocamlfuse

那里有一个如何设置环境的示例,但我是这样做的:

# Install a Drive FUSE wrapper.
!apt-get install -y -qq software-properties-common python-software-properties module-init-tools
!add-apt-repository -y ppa:alessandro-strada/ppa 2>&1 > /dev/null
!apt-get update -qq 2>&1 > /dev/null
!apt-get -y install -qq google-drive-ocamlfuse fuse


# Generate auth tokens for Colab
from google.colab import auth
auth.authenticate_user()
# Generate creds for the Drive FUSE library.
from oauth2client.client import GoogleCredentials
creds = GoogleCredentials.get_application_default()
import getpass
!google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret} < /dev/null 2>&1 | grep URL
vcode = getpass.getpass()
!echo {vcode} | google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret}

此时您已经安装了包装器,上面的代码将生成几个链接,供您授权访问您的 google 驱动器帐户。

您必须在 colab 文件系统中创建一个文件夹(请记住,据我所知,这不是永久性的...)并将您的驱动器挂载在那里:

# Create a directory and mount Google Drive using that directory.
!mkdir -p drive
!google-drive-ocamlfuse drive

print ('Files in Drive:')
!ls drive/

!ls 命令将打印目录内容,以便您检查它是否正常工作,仅此而已。您现在拥有了所需的所有文件,可以轻松地对它们进行更改。请记住,您可能需要重新启动内核以更新导入和变量。

希望这对某人有用!

要轻松上传本地文件,您可以使用新的 Google Colab 功能:

  • 点击屏幕左侧的向右箭头(Google Colab 徽标)
  • select 文件选项卡
  • 点击上传按钮

它将打开一个弹出窗口,选择要从本地文件系统上传的文件。

现在google正式提供支持,让您轻松访问和使用Gdrive。

您可以使用以下代码将您的驱动器安装到 Colab:

from google.colab import drive
drive.mount('/gdrive')
%cd /gdrive/My\ Drive/{location you want to move}

你可以在colab中编写如下命令来挂载驱动器

from google.colab import drive 
drive.mount('/content/gdrive') 

并且您可以通过简单的 linux 命令 wget 从一些外部 url 下载到驱动器中

!wget 'https://dataverse.harvard.edu/dataset'