Use Google Colaboratory to read and write files with Python, totally online
An excellent educative tool, Google Colaboratory offers the possibility to do it ALL in the cloud .
The following activity can be carried out in less than 2 minutes. You will create a data file in the cloud, write data to it, and then read from it. Everything we do will be done online, in the Cloud.
To start, create a new Google Colaboratory notebook from Google Drive:
To begin programming, create a variable with data you would like to save. In this example, we are saving employee data in CSV format. However, any data and any format could be used (i.e. JSON). Note the use of triple quotes to span multiple lines:
Now, write the employee variable to a file. It is as easy as opening a file with the parameter “w” for write access, which will overwrite it if it exists:
You will now see that the file data.txt has been created in the cloud and resides in your accessible filesystem. Remember that everything we are doing is in the Cloud:
Finally, using Linux command lines, execute the cat command. Note the use of the “!” before the command. The exclamation mark allows use to execute Linux shell commands such as !ls:
Or you could do the same using Python code with the “r” parameter indicating read access:
Google Colaboratory runs in virtual machines in the Cloud. Therefore our files will be lost or removed after approximately 12 hours or after prolonged inactivity with the notebook.
This simple tutorial has shown us how to carry out simple, but useful Python tasks, like the reading or writing of text files, totally in the Cloud using Google Colaboratory. It is a great tool for education or for quickly practicing tasks without having to setup an IDE.