Search code examples
pythonpython-3.xfilegoogle-colaboratory

Python in Google Colaboratory - How to create, write and read files in google drive


I tried using the code below to create a file but it didn't work when I tried to search it in my drive. Here is the link to my code if you need to see the full thing. https://colab.research.google.com/drive/1N436bntHOf146ZMGVBeSh5EXBuYAjvQY?usp=sharing

Here is the code I used to create and write a file.

output = open("sequences.fasta", "w")
output.writelines('>' + firstheader + '\n' + seq1 + '\n')
output.writelines('>' + secondheader + '\n' + seq2.upper() + '\n')
output.writelines('>' + thirdheader + '\n' + seq3.replace('-', '') + '\n') 

Solution

  • Setup

    You'll need to mount your google drive:

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

    I would advise you to go to the default repository for the notebooks:

    !cd '/gdrive/My Drive/Colab Notebooks/'
    

    Actual Solution

    When you are done you have to flush and unmount to see the changes in Gdrive

    drive.flush_and_unmount()
    

    Just a download

    Or you can use directly files to download it:

    from google.colab import files
    files.download('sequences.fasta')