我正在尝试将一台JupyterLab笔记本电脑迁移到Google Colab。在JupyterLab中,当我将笔记本文件和相关的csv文件放在同一个目录中时,使用numpy的loadtxt函数导入数据很容易,如下所示:
import numpy as np
filein = "testfile.csv"
data = np.loadtxt(open(filein, "rb"), delimiter=",", skiprows=1)
出于各种原因,我想继续在Colab中使用np.loadtxt。然而,当我在那里尝试相同的代码时,它找不到csv文件,尽管它与笔记本文件驻留在相同的Google Drive位置。我得到这个错误:"FileNotFoundError: [Errno 2] No such file or directory: 'testfile.csv'"
。
我想我不知何故需要提供文件的路径,但还不能弄清楚如何做到这一点。有没有什么简单的方法来使用np.loadtxt?
发布于 2019-04-01 02:18:09
Colab不会自动挂载Google Drive。默认情况下,工作目录是临时后端虚拟机上的/content
。
要访问Drive中的文件,您需要首先使用以下代码片段挂载该文件:
from google.colab import drive
drive.mount('/content/gdrive')
然后,使用%cd /content/gdrive/My\ Drive
将工作目录更改为驱动器根目录。(或者,根据需要自定义testfile.csv
所在位置的路径。)
发布于 2020-02-20 04:47:25
较短且不带命令
# mount gdrive with this code
from google.colab import drive
drive.mount('/content/drive')
#below where the file is in gdrive, change with your
data_path = "/content/drive/My Drive/Colab Notebooks/test/"
yearsBase, meanBase = np.loadtxt(data_path + 'file.csv', delimiter=',', unpack=True)
完成,没有其他代码需要ciao
https://stackoverflow.com/questions/55128156
复制相似问题