python - 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
:
在 Google Colab 内部的文件上运行ls
时,CSV 文件也被列为目录,包括0.0.0
子目录:
因此,当我尝试在 Python 中读取文件时,它会抛出IsADirectoryError
:
另一件事是在 Google Drive 的同一目录中还有两个 CSV 文件(如上面的屏幕截图所示)。它们根本不会出现在 Google Colab 中已安装的驱动器中。
SO上有一些关于IsADirectoryError
s的问题,但我发现的问题是由于实际目录。在撰写本文时,谷歌将我指向 [ this questions ] 7,显然已被删除。
为什么我的文件在 Google Drive 中显示为普通文件,但在 Google Colab 中显示为目录?子目录0.0.0
从哪里来?为什么其他两个文件在 Google Colab 中不可见?
解决方案
使用 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]))
推荐阅读
- json - Oracle SQLcl:假脱机到json,只包含项目数组中的内容?
- php - 来自 JOOMLA 的错误 403
- android - 用于 Android 和 iOS 应用程序测试自动化的工具?
- javascript - Javascript,一个带有回调处理程序的对象,如何将其重写为等待/异步样式?
- ios - 具有不同 UITableViewCells 和动态内容的 UITableView
- angular - Angular 6更改单选按钮更改标签类
- elasticsearch - 在 Elasticsearch 中使用 ngram 时如何控制结果的评分或排序?
- c++ - C++ 11 中具有多个模板参数的模板函数的特化
- c++ - Using a shared library in another shared library
- javascript - 激活弹出窗口(HTML、PHP、Javascript/Jquery)