python - 如何设置从 Google Colab 到 Google Drive 文件的路径?

标签 python google-drive-api google-colaboratory

我使用的是 Google Colab,我的代码在我的笔记本电脑中具有以下本地 CSV 文件路径:

path_csv = "C:\\Users\\Desktop\\data.csv"

我已使用以下代码将我的 Google Drive 链接到 Colab 中的笔记本:

from google.colab import drive
drive.mount('/content/gdrive')

并且我已将我的 CSV 文件上传到 Google 云端硬盘。

我的问题是用什么代替 "C:\\users\\...." 以使其在 Google Colab 中工作?

我已经尝试将 C:\\Users\\Desktop\\data.csv 替换为 /gdrive/my drive/Users\\Desktop\\data.csv" 但我收到找不到文件的错误消息。

FileNotFoundError: [Errno 2] No such file or directory:

最佳答案

您可以使用以下方式浏览已安装的 Google 云端硬盘文件夹的内容:

from google.colab import drive
drive.mount('/content/drive')

!ls /content/drive/

对我来说输出:

MyDrive

更进一步:

!ls -l /content/drive/MyDrive/

对我来说输出:

total 41
drwx------ 2 root root 4096 May  4  2017  ...
-rw------- 1 root root   18 Apr 11 02:37  data.csv
...

请注意,您应该在路径中的所有位置使用 / 而不是 \,因为 Google Colab 是基于 Linux 的系统(请参阅 Why does Windows use backslashes for paths and Unix forward slashes? )。此外,路径开头的 / 很重要。基本上,您传递给 drive.mount 的相同安装路径应该与您在其他地方使用的基本路径完全相同

因此,如果您将 data.csv 上传到 Google Drive 文件夹的顶层/根目录 ('/content/drive/MyDrive'),则它也应该出现在 /content/drive/MyDrive 目录的顶级/根目录中。

path_to_csv = '/content/drive/MyDrive/data.csv'

with open(path_to_csv) as f:
    for line in f.read().splitlines():
        print(line)

I have tried replacing C:\Users\Desktop\data.csv with /gdrive/my drive/Users\Desktop\data.csv" but i get error message that is not found.

Google 云端硬盘与您在本地 PC 上的文件夹结构不同。直观查看哪些文件和文件夹可用以及它们的组织方式的最佳方式是在浏览器上打开您的云端硬盘:https://drive.google.com/drive/my-drive

因此,例如,如果您将 data.csv 放在我的驱动器 > TEST > DATA 中:

screenshot of My Drive

那么对应的路径就是:

# Check the root folder
!ls /content/drive/

# Path should be visually same as in drive.google.com 
!ls /content/drive/MyDrive/TEST/DATA

path_to_csv = '/content/drive/MyDrive/TEST/DATA/data.csv'
MyDrive
data.csv

有关在 Colab 中使用 Google 云端硬盘的更多信息,请参阅 External data: Local Files, Drive, Sheets, and Cloud Storage 上的教程/文档:

The example below shows how to mount your Google Drive on your runtime using an authorization code, and how to write and read files there. Once executed, you will be able to see the new file (foo.txt) at https://drive.google.com/.

关于python - 如何设置从 Google Colab 到 Google Drive 文件的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67040328/

相关文章:

python - python 的 dict .get() 方法如何检查默认参数?

python - 猜数游戏新功能

python - 用作上下文管理器的 sqlite3 连接的事务不是原子的

java - Google Drive API - 创建重复文件夹

javascript - 使用 Javascript 删除 Google Drive 中的文件

python - 在 Google Colaboratory 中保存数据

python - 无法从 Google Colab 中的 keras 导入 to_categorical

python - 如何使用 SSL 在 RHEL 上编译 python3?无法导入 SSL

java - 使用输出流将文件上传到 Google Drive

python - SymPy:如何在 Google Colab 的一个单元格中输出多个 LaTex 方程?