how to save files directly in google drive in google colab

To save files directly in Google Drive using Google Colab, follow these steps:

  1. Mount Google Drive: Start by mounting your Google Drive to access it from your Colab notebook. Use the following code snippet to mount your Google Drive:
from google.colab import drive
drive.mount('/content/drive')
  1. Authenticate Google Drive: After running the code snippet, a link will be displayed. Click on the link and select your Google account. Then, copy the authorization code and paste it into the text box in the Colab notebook.

  2. Change directory: To navigate to the desired location in your Google Drive, use the cd command. For example, if you want to save your files in a folder named "Data" in the root directory of your Google Drive, use the following command:

%cd /content/drive/MyDrive/Data

Replace "Data" with the name of your desired folder.

  1. Save files: Now, you can save files directly to your Google Drive. To save a file, you can use standard file operations like open() or write(). For example, to save a text file named "example.txt", use the following code:
with open('example.txt', 'w') as f:
    f.write('This is an example file.')

Replace "example.txt" with the desired file name and modify the content as needed.

That's it! By following these steps, you can save files directly in your Google Drive using Google Colab.