将私人数据导入谷歌协作笔记本的常用方法是什么?是否可以导入一个非公开的谷歌表?不能从系统文件中读取。介绍性文档链接到使用BigQuery的指南,但这似乎有点…多。


一个演示本地文件上传/下载以及与Drive和sheets集成的官方示例笔记本可在这里获得: https://colab.research.google.com/notebooks/io.ipynb

共享文件最简单的方法是挂载您的谷歌驱动器。

要做到这一点,在代码单元格中运行以下命令:

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

它会要求您访问一个链接,以允许“谷歌文件流”访问您的驱动器。之后,一个长长的字母数字认证代码将显示,需要输入在你的Colab的笔记本。

之后,您的驱动器文件将被挂载,您可以在侧面板中的文件浏览器浏览它们。

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


最简单的方法是:

用你的数据集在github上制作存储库 克隆您的存储库![GITHUB LINK REPO] 查找数据的位置(!ls命令) 用熊猫打开文件,就像用普通的jupyter笔记本一样。


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

在gi.github.com上创建一个秘密要点,然后上传(或复制粘贴)你的文件。 单击Raw视图并复制原始文件URL。 在调用pandas.read_csv(URL)时,使用复制的URL作为文件地址

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


简单的方法从你的googledrive导入数据-这样做节省了人们的时间(不知道为什么谷歌只是没有明确地列出这一步)。

安装并验证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

Copy - ' 29pgh8xcts3mlmp6zrphvnicbv27bown ' -这是文件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)

快速,简单地从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)

上传

from google.colab import files
files.upload()

下载

files.download('filename')

目录列表

files.os.listdir()

这允许您通过谷歌驱动器上传您的文件。

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

!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}

点击出现的第一个链接,它会提示你登录谷歌;之后,另一个将出现,将要求访问您的谷歌驱动器的权限。

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

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

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

例如,如果我将我的文件abc.txt保存在我的谷歌驱动器的一个名为ColabNotebooks的文件夹中,我现在可以通过路径驱动器/ColabNotebooks/abc.txt访问它


已解决,请在这里找到详细信息,并使用下面的功能: 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!')

下面是一种从谷歌驱动器导入文件到笔记本电脑的方法。

打开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")

我希望这对你们有帮助


步骤1-挂载您的谷歌驱动器到协作实验室

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

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

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

完成了!


在任何协作的左侧栏上都有一个称为“文件”的部分。 在那里上传文件并使用此路径

"/content/YourFileName.extension"

ex: pd read_csv(“/内容/ Forbes2015。csv”);


你也可以在谷歌上使用我的实现。colab和PyDrive在https://github.com/ruelj2/Google_drive,这使它更容易。

!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()  

然后,如果你想加载谷歌驱动器目录中的所有文件,只需

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

或者只是一个特定的文件

Gd.load_file(local_dir, file_ID)

如果你想在没有代码的情况下做到这一点,这很简单。 把你的文件夹压缩到我的箱子里

dataset.zip

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

!unzip <your_zip_file_name>

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


正如@Vivek Solanki所提到的,我也在协作仪表板的“文件”部分上传了我的文件。 只需要注意文件上传的位置。对我来说, train_data = pd.read_csv('/fileName.csv')有效。


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

单击存储库中的数据集 点击“查看原始”按钮 复制链接并将其存储在一个变量中 将变量加载到Pandas read_csv中以获得数据帧

例子:

import pandas as pd
url = 'copied_raw_data_link'
df1 = pd.read_csv(url)
df1.head()

在谷歌colabs 如果这是你第一次

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

运行这些代码并遍历输出链接 然后穿过传送带到达箱子

复制时,你可以按照下面的方法复制, 转到文件右键单击并复制路径 ***不要忘记删除" /content "

f = open("drive/My Drive/RES/dimeric_force_field/Test/python_read/cropped.pdb", "r")

对于那些像我一样从谷歌搜索关键字“上传文件colab”的人:

from google.colab import files
uploaded = files.upload()

您可以通过运行以下命令挂载到谷歌驱动器 从谷歌。Colab导入驱动器 drive.mount(/内容/驱动器) 训练后复制数据从gdrive到colab根文件夹。

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

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

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


上传数据/导入数据到谷歌colab GUI方式的最佳和简单的方法是点击左边的第3个选项文件菜单图标,在那里你会得到上传浏览器文件,因为你在windows操作系统。检查下面的图像更好地容易理解。点击下面两个选项后,你会很容易地得到上传窗口框。工作。

from google.colab import files
files=files.upload()

我创建了一小段代码,可以以多种方式实现这一点。你可以

使用已经上传的文件(在重新启动内核时很有用) 使用来自Github的文件 手动上传文件

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()

Dropbox的另一种简单方法是:

把你的数据放到dropbox里

复制文件的文件共享链接

那就去合作吧。

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

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


您可以使用下面的函数。我假设您正在尝试上传一个数据帧类型的文件(.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()

这是在你没有改变谷歌合作目录的情况下,这是最简单的方法


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

将您的所有文件装入一个压缩档案谷歌驱动器。 通过链接让每个人都能看到。 从这个链接复制ID。(例如:在这个链接中https://drive.google.com/open?id=29PGh8XCts3mlMP6zRphvnIcbv27boawn ID是29PGh8XCts3mlMP6zRphvnIcbv27boawn) 进入Colab: !gdown——id 29pgh8xcts3mlmp6zrphvnicbv27bown 最后一步进入Colab: ! 解压缩file_name.zip

瞧!Colab中/content/file_name.csv中所有需要的文件都已准备就绪

对于这个简单的方法从驱动器到Colab,我感谢Gleb Mikhaylov。


从谷歌。Colab导入驱动器

驱动器(' /内容/ drive’山)

进口熊猫作为pd dv = pd.read_csv(' /内容/传动/ MyDrive /戴安娜/卡索/ Data_Caso_Propuesto.csv”) dv.info ()