186

将私有数据导入 Google Colaboratory 笔记本的常用方法有哪些?是否可以导入非公开的 Google 表格?您无法从系统文件中读取。介绍性文档链接到使用 BigQuery 的指南,但这似乎有点……很多。

4

23 回答 23

233

此处提供了演示本地文件上传/下载以及与 Drive 和工作表集成的官方示例笔记本: https ://colab.research.google.com/notebooks/io.ipynb

共享文件的最简单方法是挂载您的 Google Drive。

为此,请在代码单元格中运行以下命令:

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

它会要求您访问一个链接以允许“Google 文件流”访问您的驱动器。之后,将显示一个长的字母数字身份验证代码,需要将其输入到 Colab 的笔记本中。

之后,您的云端硬盘文件将被挂载,您可以使用侧面板中的文件浏览器浏览它们。

在此处输入图像描述

这是一个完整的示例笔记本

于 2017-10-30T16:13:42.863 回答
65

上传

from google.colab import files
files.upload()

下载

files.download('filename')

列表目录

files.os.listdir()
于 2018-03-14T10:50:04.847 回答
23

第 1 步 - 将您的 Google Drive 安装到 Collaboratory

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

第 2 步 - 现在您将在左侧窗格(文件资源管理器)中看到您的 Google Drive 文件。右键单击需要导入的文件并选择 çopy 路径。然后像往常一样在 pandas 中导入,使用这个复制的路径。

import pandas as pd
df=pd.read_csv('gdrive/My Drive/data.csv')

完毕!

于 2018-11-13T13:59:20.863 回答
20

从您的 googledrive 导入数据的简单方法 - 这样做可以节省人们的时间(不知道为什么 google 没有明确列出这一步骤)。

安装并验证 PYDRIVE

     !pip install -U -q PyDrive ## you will have install for every colab session

     from pydrive.auth import GoogleAuth
     from pydrive.drive import GoogleDrive
     from google.colab import auth
     from oauth2client.client import GoogleCredentials

     # 1. Authenticate and create the PyDrive client.
     auth.authenticate_user()
     gauth = GoogleAuth()
     gauth.credentials = GoogleCredentials.get_application_default()
     drive = GoogleDrive(gauth)

上传

如果您需要从本地驱动器上传数据:

    from google.colab import files

    uploaded = files.upload()

    for fn in uploaded.keys():
       print('User uploaded file "{name}" with length {length} bytes'.format(name=fn, length=len(uploaded[fn])))

执行,这将显示一个选择文件按钮-找到您的上传文件-单击打开

上传后会显示:

    sample_file.json(text/plain) - 11733 bytes, last modified: x/xx/2018 - %100 done
    User uploaded file "sample_file.json" with length 11733 bytes

为笔记本创建文件

如果您的数据文件已经在您的 gdrive 中,您可以跳到此步骤。

现在它在你的谷歌驱动器中。在您的谷歌驱动器中找到该文件并右键单击。点击获取“可共享链接”。你会得到一个窗口:

    https://drive.google.com/open?id=29PGh8XCts3mlMP6zRphvnIcbv27boawn

复制 - '29PGh8XCts3mlMP6zRphvnIcbv27boawn' - 这是文件 ID。

在你的笔记本中:

    json_import = drive.CreateFile({'id':'29PGh8XCts3mlMP6zRphvnIcbv27boawn'})

    json_import.GetContentFile('sample.json') - 'sample.json' is the file name that will be accessible in the notebook.

将数据导入笔记本

要将您上传的数据导入笔记本(本示例中的 json 文件 - 您加载的方式取决于文件/数据类型 - .txt、.csv 等):

    sample_uploaded_data = json.load(open('sample.json'))

现在您可以打印以查看数据是否存在:

    print(sample_uploaded_data)
于 2018-02-20T23:58:15.823 回答
7

我做的最简单的方法是:

  1. 使用您的数据集在 github 上创建存储库
  2. 克隆您的存储库!git clone --recursive [GITHUB LINK REPO]
  3. 查找您的数据在哪里(!ls 命令)
  4. 就像在普通的 jupyter 笔记本中一样,用 pandas 打开文件。
于 2018-02-10T18:50:53.690 回答
7

这允许您通过 Google Drive 上传文件。

运行下面的代码(之前在某个地方找到了这个,但我再也找不到源代码了——感谢编写它的人!):

!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

from google.colab import auth
auth.authenticate_user()
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;之后会出现另一个请求访问您的 Google Drive 的权限。

然后,运行它会创建一个名为“drive”的目录,并将您的 Google Drive 链接到它:

!mkdir -p drive
!google-drive-ocamlfuse drive

如果!ls现在执行,将会有一个目录驱动器,如果执行,!ls drive您可以看到 Google Drive 的所有内容。

例如,如果我将我的文件保存在我的 Google Driveabc.txt中的一个文件夹ColabNotebooks中,我现在可以通过路径访问它drive/ColabNotebooks/abc.txt

于 2018-03-17T02:31:09.150 回答
6

在任何合作实验室的左侧栏上都有一个名为“文件”的部分。在那里上传您的文件并使用此路径

"/content/YourFileName.extension"

前任:pd.read_csv('/content/Forbes2015.csv');

于 2018-11-19T03:50:03.037 回答
6

上传数据/将数据导入 Google colab GUI 的最佳且最简单的方法是单击最左侧的第三个选项文件菜单图标,然后您将在 Windows 操作系统中上传浏览器文件。检查下面的图像以便更好地理解。单击以下两个选项后,您将轻松获得上传窗口框。完成工作。 在此处输入图像描述

from google.colab import files
files=files.upload()
于 2020-08-01T12:43:25.730 回答
5

从 Dropbox 快速轻松地导入:

!pip install dropbox
import dropbox
access_token = 'YOUR_ACCESS_TOKEN_HERE' # https://www.dropbox.com/developers/apps
dbx = dropbox.Dropbox(access_token)

# response = dbx.files_list_folder("")

metadata, res = dbx.files_download('/dataframe.pickle2')

with open('dataframe.pickle2', "wb") as f:
  f.write(res.content)
于 2018-03-09T20:17:02.940 回答
3

到目前为止,我发现的最适合中小型 CSV 文件的最简单的解决方案是:

  1. 在 gist.github.com 上创建一个秘密要点并上传(或复制粘贴)您的文件。
  2. 单击原始视图并复制原始文件 URL。
  3. 调用时使用复制的 URL 作为文件地址pandas.read_csv(URL)

这对于逐行读取文本文件或二进制文件可能有效,也可能无效。

于 2018-02-19T22:59:36.063 回答
3

对于那些像我一样来自 Google 的关键字“上传文件 colab”的人:

from google.colab import files
uploaded = files.upload()
于 2020-03-27T15:59:06.490 回答
1

如果这是您第一次在 google colabs 中,

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

运行这些代码并通过 outputlink 然后通过 pass-prase 到盒子

复制时可以如下复制,文件右键复制路径***别忘了去掉“/content”

f = open("drive/My Drive/RES/dimeric_force_field/Test/python_read/cropped.pdb", "r")
于 2020-02-24T23:26:23.300 回答
1

您还可以在https://github.com/ruelj2/Google_drive上使用我在 google.colab 和 PyDrive 上的实现,这样会更容易。

!pip install - U - q PyDrive  
import os  
os.chdir('/content/')  
!git clone https://github.com/ruelj2/Google_drive.git  

from Google_drive.handle import Google_drive  
Gd = Google_drive()  

然后,如果您想加载 Google Drive 目录中的所有文件,只需

Gd.load_all(local_dir, drive_dir_ID, force=False)  

或者只是一个特定的文件

Gd.load_file(local_dir, file_ID)
于 2018-11-19T05:11:24.253 回答
1

我创建了一小段代码,可以通过多种方式做到这一点。你可以

  1. 使用已经上传的文件(重启内核时有用)
  2. 使用来自 Github 的文件
  3. 手动上传文件
import os.path

filename = "your_file_name.csv"
if os.path.isfile(filename):
  print("File already exists. Will reuse the same ...")
else:
  use_github_data = False  # Set this to True if you want to download from Github
  if use_github_data:
    print("Loading fie from Github ...")
    # Change the link below to the file on the repo
    filename = "https://github.com/ngupta23/repo_name/blob/master/your_file_name.csv" 
  else:
    print("Please upload your file to Colab ...")
    from google.colab import files
    uploaded = files.upload()
于 2020-08-07T09:57:46.740 回答
1
  1. 您可以通过运行以下命令安装到谷歌驱动器

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

  2. 之后用于训练将数据从 gdrive 复制到 colab 根文件夹。

!cp -r '/content/drive/My Drive/Project_data' '/content'

其中第一个路径是 gdrive 路径,第二个是 colab 根文件夹。

这种方式对于大数据的训练速度更快。

于 2020-06-25T14:17:50.607 回答
1

正如@Vivek Solanki 所提到的,我还在“文件”部分下的协作仪表板上上传了我的文件。只需记下文件的上传位置即可。对我来说, train_data = pd.read_csv('/fileName.csv')工作。

于 2019-09-10T04:52:02.047 回答
0

这是将文件从谷歌驱动器导入笔记本的一种方法。

打开 jupyter notebook 并运行以下代码并完成身份验证过程

!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
from google.colab import auth
auth.authenticate_user()
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}

一旦你完成了上面的代码,运行下面的代码来挂载谷歌驱动器

!mkdir -p drive
!google-drive-ocamlfuse drive

将文件从谷歌驱动器导入笔记本(例如:Colab_Notebooks/db.csv)

假设您在 Colab_Notebooks 文件夹中的数据集文件,其名称为 db.csv

import pandas as pd
dataset=pd.read_csv("drive/Colab_Notebooks/db.csv")

我希望它有帮助

于 2018-07-14T18:00:45.640 回答
0

如果你想在没有代码的情况下做到这一点,这很容易。在我的情况下压缩你的文件夹

数据集.zip

然后在 Colab 中右键单击要放置此文件的文件夹,然后按 Upload 并上传此 zip 文件。之后编写这个 Linux 命令。

!unzip <your_zip_file_name>

您可以看到您的数据已成功上传。

于 2019-03-04T18:30:38.700 回答
0

如果数据集大小小于 25mb,上传 CSV 文件的最简单方法是从您的 GitHub 存储库。

  1. 单击存储库中的数据集
  2. 点击查看原始按钮
  3. 复制链接并将其存储在变量中
  4. 将变量加载到 Pandas read_csv 中以获取数据帧

例子:

import pandas as pd
url = 'copied_raw_data_link'
df1 = pd.read_csv(url)
df1.head()
于 2020-02-12T14:12:54.417 回答
0

已解决,请在此处查找详细信息,请使用以下功能: https ://stackoverflow.com/questions/47212852/how-to-import-and-read-a-shelve-or-numpy-file-in-google -colaboratory/49467113#49467113

from google.colab import files
import zipfile, io, os

    def read_dir_file(case_f):
        # author: yasser mustafa, 21 March 2018  
        # case_f = 0 for uploading one File and case_f = 1 for uploading one Zipped Directory
        uploaded = files.upload()    # to upload a Full Directory, please Zip it first (use WinZip)
        for fn in uploaded.keys():
            name = fn  #.encode('utf-8')
            #print('\nfile after encode', name)
            #name = io.BytesIO(uploaded[name])
        if case_f == 0:    # case of uploading 'One File only'
            print('\n file name: ', name)
            return name
        else:   # case of uploading a directory and its subdirectories and files
            zfile = zipfile.ZipFile(name, 'r')   # unzip the directory 
            zfile.extractall()
            for d in zfile.namelist():   # d = directory
                print('\n main directory name: ', d)
                return d
    print('Done!')
于 2018-03-24T16:35:46.570 回答
0

使用 Dropbox 的另一种简单方法是:

将您的数据放入保管箱

复制文件的文件共享链接

然后在colab中做wget。

例如:!wget - O 文件名文件链接(如 - https://www.dropbox.com/.....

你完成了。数据将开始出现在您的 colab 内容文件夹中。

于 2021-05-09T08:14:00.427 回答
0

Colab 中只有两行代码。非常简单的方法:

  1. 将一个压缩包中的所有文件加载到 Google 云端硬盘。
  2. 通过链接让每个人都可以看到它。
  3. 从此链接复制 ID。(例如:在这个链接https://drive.google.com/open?id=29PGh8XCts3mlMP6zRphvnIcbv27boawn ID 是29PGh8XCts3mlMP6zRphvnIcbv27boawn
  4. 进入 Colab: !gdown --id 29PGh8XCts3mlMP6zRphvnIcbv27boawn
  5. 最后一步进入 Colab: ! unzip file_name.zip

瞧!所有需要的文件都已准备好在 Colab 中使用/content/file_name.csv

对于这种将文件从 Drive 获取到 Colab 的简单方法,我感谢 Gleb Mikhaylov。

于 2021-12-17T14:05:50.123 回答
0

您可以使用以下功能。我假设您正在尝试上传数据框类型的文件(.csv、.xlsx)

def file_upload():
    file = files.upload()
    path = f"/content/{list(file.keys())[0]}"
    df = pd.read_excel(path)
    return df

#your file will be saved in the variable: dataset
dataset = file_upload()

如果您没有更改 google collab 的目录,那么这是最简单的方法

于 2021-10-27T07:10:23.637 回答