有很多方法可以读取 colab notebook(**.ipnb) 中的文件,其中一些是:
- 在运行时的虚拟机中挂载您的 Google Drive。这里&这里
- 使用 google.colab.files.upload()。最简单的解决方案
- 使用本机 REST API;
- 使用 API 的包装器,例如PyDrive
方法1和2 对我有用,其余我无法弄清楚。如果有人可以,就像其他人在上面的帖子中尝试的那样,请写一个优雅的答案。提前致谢。!
第一种方法:
我无法安装我的谷歌驱动器,所以我安装了这些库
# Install a Drive FUSE wrapper.
# https://github.com/astrada/google-drive-ocamlfuse
!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
安装后我可以挂载谷歌驱动器,你的谷歌驱动器中的所有内容都从/content/drive
!ls /content/drive/ML/../../../../path_to_your_folder/
现在,您可以path_to_your_folder
使用上述路径简单地将文件夹中的文件读入 pandas。
import pandas as pd
df = pd.read_json('drive/ML/../../../../path_to_your_folder/file.json')
df.head(5)
你假设你使用你收到的绝对路径而不是使用 /../..
第二种方法:
如果您要读取的文件存在于当前工作目录中,这很方便。
如果您需要从本地文件系统上传任何文件,您可以使用下面的代码,否则就避免它。!
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])))
假设您在 google 驱动器中的文件夹层次结构之下:
/content/drive/ML/../../../../path_to_your_folder/
然后,您只需将以下代码加载到 pandas 中。
import pandas as pd
import io
df = pd.read_json(io.StringIO(uploaded['file.json'].decode('utf-8')))
df