pythongoogle-colaboratory

Files and Folders in Google Colab


I just started using Google colab for my projects and I tried to create and parse text files. But I don't quite understand how the file directory works here. Below are my questions:

  1. On the left navigation pane (in the picture) that show the list of folders and files. Are they in my drive, if they are, where they are located? How can I find?
  2. How do I create/upload a file and store in google drive in order to parse it in my app? I have created one file in the folder "Contents" yesterday. But I woke up this morning, it's gone. Can anyone explain what happened?

Appreciate your time, thank you.

enter image description here


Solution

  • The google colab folders are temporary and they will disappear after 8 hours I think. You need to save them to your mounted google drive location. The content folder is part of colab and will be deleted.

    You need to mount google drive to your Colab session.

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

    Then you can write to google drive like

    with open('/content/gdrive/My Drive/file.txt', 'w') as f:
        f.write('content')
    
    

    Or even save stuff like pandas files to csv there like

    df.to_csv('/content/gdrive/My Drive/file.csv')
    
    

    You can also read files from there like this

    import pandas as pd
    df = pd.read_csv('/content/gdrive/My Drive/file.csv')
    

    All of this will only work after you mount the drive of course.