将私人数据导入谷歌协作笔记本的常用方法是什么?是否可以导入一个非公开的谷歌表?不能从系统文件中读取。介绍性文档链接到使用BigQuery的指南,但这似乎有点…多。
当前回答
步骤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')
完成了!
其他回答
这允许您通过谷歌驱动器上传您的文件。
运行下面的代码(之前在某个地方找到了这个,但我再也找不到源代码了——归功于写它的人!):
!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!')
Dropbox的另一种简单方法是:
把你的数据放到dropbox里
复制文件的文件共享链接
那就去合作吧。
例如: ! wget - O文件名文件链接(如- https://www.dropbox.com/.....)
做完了。数据将开始出现在您的colab内容文件夹中。
到目前为止,我发现的最简单的解决方案,适用于中小型CSV文件是:
在gi.github.com上创建一个秘密要点,然后上传(或复制粘贴)你的文件。 单击Raw视图并复制原始文件URL。 在调用pandas.read_csv(URL)时,使用复制的URL作为文件地址
这对于逐行读取文本文件或二进制文件可能有效,也可能无效。
你也可以在谷歌上使用我的实现。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)