I'm trying to migrate a JupyterLab notebook to Google Colab. In JupyterLab, when I have the notebook file and the associated csv files in the same directory, it is easy to import the data using numpy's loadtxt function as follows:
import numpy as np
filein = "testfile.csv"
data = np.loadtxt(open(filein, "rb"), delimiter=",", skiprows=1)
For various reasons I'd like to continue to use np.loadtxt in Colab. However when I try the same code there, it can't find the csv file despite it residing in the same Google Drive location as the notebook file. I get this error: "FileNotFoundError: [Errno 2] No such file or directory: 'testfile.csv'"
.
I gather I somehow need to provide a path to the file, but haven't been able to figure out how to do this. Is there any straightforward way to use np.loadtxt?
Colab doesn't automatically mount Google Drive. By default, the working directory is /content
on an ephemeral backend virtual machine.
To access your file in Drive, you'll need to mount it first using the following snippet:
from google.colab import drive
drive.mount('/content/gdrive')
Then, %cd /content/gdrive/My\ Drive
to change the working directory to your Drive root. (Or, customize the path as needed to wherever testfile.csv
is located.)
Shorter and without command
# 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)
done, no other code needed ciao
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With