Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you import a .txt (or other file type) into a Google Colab notebook directly from your own Drive?

I'm trying to import a couple .txt files into Colab from my own Google Drive. The colab notebook I'm using is in the same folder as the files I want to upload within that notebook. While there is documentation on file I/O on External data: Local Files, Drive, Sheets, and Cloud Storage within Colab, the descriptions do not seem to fit what I'm looking for (e.g. I could upload these files directly from my local directory each time I use the notebook, but instead, I would like to have a cell written that loads them once and keeps them loaded via a connection to my own Drive). Also, the .txt files I want to upload contain samples of plain text to use for training a deep learning algorithm on sentiment analysis, and thus does not appear to be convertable to a .csv for functionally equivalent application (which might be solved by Google Sheets).

From External data: Local Files, Drive, Sheets, and Cloud Storage, the options are 1) uploading from a local directory, 2) mounting to Drive locally/using an API, or 3) importing from Google Sheets or Google Cloud Storage. Of these, I have tried 1 and some of 2, but because I am still relatively new to Python and Colab, the documentation of 2 and 3 are confusing and do not clearly direct me to a solution. Thus, it is possible that my problem is an interpretation problem, in which case showing how 2/3 could solve it would be quite helpful.

I'm thinking it should be possible to refer to these .txt files within Colab since both the colab notebook and .txt files are in the same Drive folder, but perhaps I'm overly comparing the cell functionality of Colab with navigating files in a directory in your everyday terminal.

like image 569
Damien Desmond Avatar asked Nov 19 '25 14:11

Damien Desmond


1 Answers

If you have a file that you want to write in the root of your Google Drive called foo.txt then the following code should read the file into Colab:

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

The above will ask you to provide your credentials via a link in the cell output. Once you have authorized this access, you can run the following in another cell to write Hello Google Drive! to a text file called foo.txt in your Google Drive:

with open('/content/drive/My Drive/foo.txt', 'w') as f: 
    f.write('Hello Google Drive!')

To read a text file from Google Drive called foo.txt in your Google Drive drive you can similarly use:

with open('/content/drive/My Drive/foo.txt', 'r') as f: 
    print(f.read())

If one runs this reading code after having written to foo.txt this should output Hello Google Drive!

like image 123
user3147395 Avatar answered Nov 21 '25 03:11

user3147395



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!