Search code examples
pythoncsvsavegoogle-colaboratory

How to write and save csv files in a loop on google colab?


I'm trying to create and save multiple csv files (in a loop, 1 file per iteration) on a google colab notebook. I'm using

drive.mount('/drive')
f3.to_csv('/drive/My Drive/Colab Notebooks/data/file.csv', index =False)

But obviously it's not working. the cell is giving me a text box to enter my authorization code. Is there a way around this to save files in a loop?

To make it clear, here's the code

for k in portkey:
 f3 = f2[f2.port_key_anonymised == k]
 if f3.shape[0]>0 :
  drive.mount('/drive')
  f3.to_csv('/drive/My Drive/Colab Notebooks/data/'+str(nb)+'.csv', index =False)

Thank you!


Solution

  • You need to mount the drive only once by providing the authorization code. After that, you have access to the file system and can read and write multiple files.

    Your code should look something like this

    # Mount drive
    drive.mount('/drive')
    
    # Save multiple CSV files
    for k in portkey:
     f3 = f2[f2.port_key_anonymised == k]
     if f3.shape[0]>0 :
      # Save file
      f3.to_csv('/drive/My Drive/Colab Notebooks/data/'+str(nb)+'.csv', index =False)