如何将 csv 文件从 google 云端硬盘上传(并使用它)到 google colaboratory

2024-01-01

想尝试一下 python 和 google colaboratoryseemed最简单的选择。我的谷歌驱动器中有一些文件,想将它们上传到谷歌合作实验室。 所以这是我正在使用的代码:

!pip install -U -q PyDrive

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)

# 2. Create & upload a file text file.
uploaded = drive.CreateFile({'xyz.csv': 'C:/Users/abc/Google Drive/def/xyz.csv'})
uploaded.Upload()
print('Uploaded file with title {}'.format(uploaded.get('title')))

import pandas as pd
xyz = pd.read_csv('Untitled.csv')

基本上,对于用户“abc”,我想从文件夹“def”上传文件 xyz.csv。 我可以上传文件,但是当我询问标题时,它说标题是“无标题”。 当我询问上传文件的ID时,它每次都会改变,所以我无法使用该ID。

我如何读取文件???并设置正确的文件名???

xyz = pd.read_csv('Untitled.csv') doesnt work
xyz = pd.read_csv('Untitled') doesnt work
xyz = pd.read_csv('xyz.csv') doesnt work

这是我发现的一些其他链接..

如何在 Google Colaboratory 中导入并读取 shelve 或 Numpy 文件? https://stackoverflow.com/questions/47212852/how-to-import-and-read-a-shelve-or-numpy-file-in-google-colaboratory

将本地数据文件加载到Colaboratory https://stackoverflow.com/questions/47320052/load-local-data-files-to-colaboratory


要将 csv 文件从我的 google 驱动器读取到 colaboratory,我需要执行以下步骤:

1)我首先需要授权 colaboratory 使用 PyDrive 访问我的 google 驱动器。我为此使用了他们的代码示例。 (粘贴在下面)

2) 我还需要登录我的drive.google.com 来查找我想要下载的文件的目标ID。我通过右键单击该文件并复制 ID 的共享链接找到了这一点。 ID 看起来像这样:“1BH-rffqv_1auzO7tdubfaOwXzf278vJK”

3)然后我跑了 download.GetContentFile('myName.csv') - 输入我想要的名称(在你的情况下是 xyz.csv)

这似乎对我有用!

我使用了他们在示例中提供的代码:

# Code to read csv file into colaboratory:
!pip install -U -q PyDrive
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)

#2. Get the file
downloaded = drive.CreateFile({'id':'1BH-rffqv_1auzO7tdubfaOwXzf278vJK'}) # replace the id with id of file you want to access
downloaded.GetContentFile('xyz.csv')  

#3. Read file as panda dataframe
import pandas as pd
xyz = pd.read_csv('xyz.csv') 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 csv 文件从 google 云端硬盘上传(并使用它)到 google colaboratory 的相关文章

随机推荐