首页 > 解决方案 > Google Drive 中的文件作为 Collab 中的目录装载

问题描述

我正在尝试访问托管在 Google Colab 笔记本中的 Google Drive 中的 CSV 文件。如文档中所述,我通过 Web UI 安装我的个人驱动器。Drive 内容(几乎)按预期显示在侧边栏中。但是,不完全是,因为 CSV 文件在 Google Colab 中显示为一个目录。

此屏幕截图显示了我的 Google Drive 中的 CSV 文件: 谷歌云端硬盘

我可以从 Google Drive 下载文件,内容是预期的 CSV 文件。

此屏幕截图显示了文件在 Google Colab 文件浏览器中的显示方式,就像一个目录,包括一个子目录0.0.0谷歌 Colab 树

在 Google Colab 内部的文件上运行ls时,CSV 文件也被列为目录,包括0.0.0子目录:谷歌 Colab ls

因此,当我尝试在 Python 中读取文件时,它会抛出IsADirectoryError在此处输入图像描述

另一件事是在 Google Drive 的同一目录中还有两个 CSV 文件(如上面的屏幕截图所示)。它们根本不会出现在 Google Colab 中已安装的驱动器中。

SO上有一些关于IsADirectoryErrors的问题,但我发现的问题是由于实际目录。在撰写本文时,谷歌将我指向 [ this questions ] 7,显然已被删除。

为什么我的文件在 Google Drive 中显示为普通文件,但在 Google Colab 中显示为目录?子目录0.0.0从哪里来?为什么其他两个文件在 Google Colab 中不可见?

标签: pythongoogle-drive-apigoogle-colaboratory

解决方案


使用 os 库以这种方式尝试。

from google.colab import drive 
import os
import pandas as pd

安装驱动器

drive.mount('/content/drive')

打印文件名并记下文件索引

path = "/content/drive/MyDrive/data/educational_classifier"
fnames = os.listdir(path)
print(fnames)

输出应该是:['file1.csv', 'file2.csv', 'file3.csv']

使用索引读取文件

df = pd.read_csv(os.path.join(path, fnames[index]))

例如:df = pd.read_csv(os.path.join(path, fnames[3]))


推荐阅读