Importing CSV file into Google Colab using numpy loadtxt Importing CSV file into Google Colab using numpy loadtxt numpy numpy

Importing CSV file into Google Colab using numpy 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 drivedrive.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 codefrom google.colab import drivedrive.mount('/content/drive')#below where the file is in gdrive, change with yourdata_path = "/content/drive/My Drive/Colab Notebooks/test/"yearsBase, meanBase = np.loadtxt(data_path + 'file.csv', delimiter=',', unpack=True)

done, no other code neededciao


Here's another way that has lesser manual intervention. This is more useful if you intend to run the colab notebook for a long time across multiple disconnected sessions so that you don't need to manually upload the file every time.

  1. Upload the text file to google drive. Click share and obtain the shareable link. For example, this is an example shareable link for the file iris.csv: https://drive.google.com/file/d/1Llp483f91dAJriuE6PanmecLA9sWDPyi/view

  2. Copy the file ID from the above link. In this case, it is 1Llp483f91dAJriuE6PanmecLA9sWDPyi

  3. Now you can download the file using the below cell in any colab notebook:

    file_id = "1Llp483f91dAJriuE6PanmecLA9sWDPyi" # replace with your ID!gdown https://drive.google.com/uc?id={file_id}

Type !ls to see the file in your workspace.

For a detailed official guide, refer this notebook: https://colab.research.google.com/notebooks/io.ipynb