Importing local files in Google Colab
As I mentioned in above post for Colab starters, Google Colab is an EASY, FREE, ACCESSIBLE, and SOCIAL way to code Python and implement machine learning algorithms.
In this post, we explore how to import files ( csv, txt, or json format) in Colab.
Importing CSV / TXT files
CSV or TXT files are most common formats for sharing data. Importing CSV and TXT files are largely similar.
1. Upload file
To upload file, files module under google.colab should be imported in advance. Then use files.upload() function to upload CSV or TXT file. You could select the file by clicking the grey button and choose the file by clicking.
Uploaded file is in Python dictionary format, with key as name of uploaded file and corresponding value as the contents of the file.
Note that in this case, each line is separated by \r\n .
2. Decode file
One way is to directly decode the contents using decode() function and separate each sentence using split() function. Result is a list with each element as contents in each line of the dataset.
3. Parse data
We can further separate each features in line using split() function again.
Using Pandas
Another way is to use pandas and io packages. This is slightly simpler with high-level functions. First convert dataset into StringIO object.
Then, parse the dataset using read_csv() function. Note that result is pandas dataframe , instead of 2-D list like above method.
Importing JSON files
JSON is another common file format to share datasets. When importing JSON files in Python, we fall back on json library.
1. Upload data
2. Decode file
Decode and create StringIO object.
3. Parse file
JSON file can be easily parsed using json.loads() function. Result is Python dictionary, which is pretty similar data structure to JavaScript Object.
Code in this post can be exhibited by below link. \
And more
In this post, I have shown you ways to upload local files in Google Colab. However, this is not the only way, and not the easiest either. As you know, Colab is one of the applications embedded in Google Drive. By taking advantage of such fact, we can easily import files that are in your Google Drive. In next post, I will cover how to import files from Google Drive.
Управление файлами в Google Colab
Google Colaboratory — бесплатная среда Jupyter Notebook, которая выполняется на облачных серверах Google и позволяет использовать аппаратное оборудование бэкенда, например GPU and TPU. В результате вы можете работать со всеми возможностями Jupyter Notebook, не устанавливая его на локальной машине.
Colab поставляется (почти) со всеми настройками, позволяющими начать процесс программирования, за исключением датасетов. Как же с помощью Colab получить к ним доступ?
В данной статье мы рассмотрим:
- как загружать данные в Colab из разных источников;
- как произвести обратную запись из Colab в эти источники данных;
- ограничения Google Colab при работе с внешними файлами.
Операции с директориями и файлами в Google Colab
Поскольку Colab позволяет делать все, что угодно, в локально размещенном Jupyter Notebook, то появляется возможность работать с командами оболочки, такими как ls , dir , pwd , cd , cat , echo и т.д., с помощью магической команды для строки ( % ) или bash-команды ( ! ).
Для просмотра структуры директории воспользуйтесь панелью файлового менеджера слева.
Как загружать и скачивать файлы в/из Google Colab
Поскольку блокнот Colab размещается на облачных серверах Google, то по умолчанию отсутствует прямой доступ к файлам на вашем локальном диске (в отличие от расположенного на компьютере блокнота) или в любой другой среде.
Однако Colab предоставляет разные варианты подключения к практически любому источнику данных. Посмотрим, как это происходит.
Обращение к GitHub из Google Colab
Вы можете либо клонировать весь репозиторий GitHub в среду Colab, либо получить доступ к отдельным файлам по их необработанной ссылке.
Клонирование репозитория GitHub
Клонирование репозитория Github в среду Colab происходит по такому же принципу, как и на локальный компьютер, а именно с помощью git clone . По завершении этой процедуры обновите менеджер файлов для просмотра содержимого.
И теперь файлы можно читать точно так же, как и на локальном компьютере.
Скачивание отдельных файлов непосредственно с GitHub
Если для работы нужно лишь несколько файлов, а не весь репозиторий, то можно обойтись без его клонирования в Colab и скачать эти файлы непосредственно с GitHub.
- Кликните на файл в репозитории.
- Кликните на View Raw.
- Скопируйте URL необработанного файла.
- Используйте этот URL как местоположение файла.
Обращение к локальной файловой системе через Google Colab
Читать и записывать файлы из/в локальную файловую систему можно с помощью менеджера или кода Python.
Обращение к локальным файлам через менеджер файлов
Загрузка файлов из локальной файловой системы через менеджер
Для загрузки любых файлов из локальной файловой системы в текущую рабочую директорию Colab можно воспользоваться опцией Upload в верхней части панели менеджера файлов.
Для загрузки файлов напрямую в поддиректорию нужно:
- Кликнуть на три точки, появляющиеся при наведении курсора на каталог.
- Выбрать опцию Upload.
3. Выбрать файлы для загрузки из диалогового окна File Upload.
4. Подождать завершения загрузки, процесс выполнения которой отображается в нижней части панели менеджера файлов.
По окончании процесса загрузки читать файлы можно привычным для вас способом.
Скачивание файлов в локальную файловую систему через менеджер файлов
Кликните на три точки, появляющиеся при наведении курсора на имя файла и выберите опцию Download.
Обращение к локальной файловой системе посредством кода Python
Для осуществления этого шага предварительно требуется импортировать модуль files из google.colab library :
Загрузка файлов из локальной файловой системы посредством кода Python
Применяем метод загрузки объекта files :
В результате открывается диалоговое окно File Upload:
Выбираем файлы для загрузки и ждем завершения. Ход ее выполнения отображается:
Объект uploaded является словарем, где имена файлов и их содержимое хранятся в виде пар “ключ-значение”:
По окончании загрузки считать его можно точно так же, как и любой другой файл из Colab:
Также есть способ считать его напрямую из директории uploaded , используя библиотеку io :
Убедитесь, что имя файла соответствует тому файлу, который вы хотите скачать.
Скачивание файлов из Colab в локальную систему посредством кода Python
Применение метода download объекта files позволяет скачать любой файл из Colab на локальный диск. Процесс выполнения отображается, и по его завершении можно выбрать на локальном компьютере место для сохранения файла.
Обращение к Google Диску из Google Colab
Рассмотрим пошагово, как с помощью модуля drive из google.colab можно смонтировать весь Google Диск в Colab:
1. Выполняем следующий код с целью получения ссылки для аутентификации:
2. Открываем ссылку.
3. Выбираем аккаунт Google, диск которого нужно смонтировать.
4. Разрешаем Google Drive Stream доступ к вашему аккаунту Google.
5. Копируем отображенный код, вставляем его в текстовое окно, как показано ниже, и нажимаем Enter.
По окончании монтирования получаем сообщение “Mounted at /content/gdrive” (”Смонтировано в/содержимое/gdrive”), после чего можно просматривать содержимое диска из панели менеджера файлов.
Теперь взаимодействовать с Google Диск можно точно так же, как и с каталогом в среде Colab. Любые изменения, связанные с этим каталогом, будут сразу же отображаться на Google Диске, файлы которого вы можете читать как и любые другие.
Кроме того, можно даже напрямую делать запись из Colab на Google Диск, применяя обычные операции с файлами/каталогами.
Эта команда создаст файл на Google Диске, который отобразится на панели менеджера файлов при ее обновлении:
Обращение к Google Таблицам из Google Colab
Для обращения к Google Таблицам:
- Прежде всего, необходимо аутентифицировать аккаунт для соединения с Colab. С этой целью выполняем следующий код:
2. В результате получаем ссылку для аутентификации и открываем ее.
3. Выбираем аккаунт Google для соединения.
4. Разрешаем Google Cloud SDK доступ к вашему аккаунту Google.
5. Наконец, копируем отображаемый код, вставляем его в текстовое окно и нажимаем Enter.
Для взаимодействия с Google Таблицами потребуется импортировать предустановленную библиотеку gspread. Чтобы разрешить ей доступ к вашему аккаунту Google воспользуемся методом GoogleCredentials из предустановленной библиотеки oauth2client.client:
После выполнения кода в текущей рабочей директории будет создан файл adc.json с учетными данными, которые нужны gspread для получения доступа к вашему аккаунту Google.
Теперь создавайте или скачивайте Google таблицы напрямую из среды Colab.
Создание/обновление Google таблицы в Colab
- Создаем рабочую книгу с помощью метода create объекта gc :
2. Как только она готова, можно ее посмотреть на sheets.google.com.
3. Прежде всего, открываем рабочую книгу для записи в нее значений:
4. Затем выбираем ячейки для заполнения:
5. Таким образом мы создаем список ячеек с индексами (R1C1) и значениями (на данный момент пустыми). Можно изменить отдельные ячейки, обновив их атрибут значения:
6. Для обновления этих ячеек в рабочей таблице применяем метод update_cells :
7. Все изменения отображаются в вашей Google таблице.
Скачивание данных из Google таблицы
1. Открываем рабочую книгу с помощью метода open объекта gc :
2. Затем считываем все строки отдельной рабочей таблицы, задействуя метод get_all_values :
3. Для загрузки этих данных в датафрейм задействуем метод from_record объекта DataFrame :
Обращение к Google Cloud Storage (GCS) из Google Colab
Для работы с GCS необходим проект Google Cloud (GCP). Вы можете создавать и подключаться к корзинам GCS в Colab через предустановленную утилиту командной строки gsutil .
1. Сначала указываем ID проекта:
2. Для доступа к GCS проводим аутентификацию вашего аккаунта Google:
3. Выполнив вышеуказанный код, получаем ссылку для аутентификации и открываем ее.
4. Выбираем аккаунт Google для соединения.
5. Разрешаем доступ Google Cloud SDK к вашему аккаунту Google.
6. Теперь копируем отображаемый код, вставляем его в текстовое окно и нажимаем Enter.
7. Затем настраиваем gsutil для работы с проектом:
8. Вы можете создать корзину с помощью соответствующей команды mb (“make bucket”). У корзин GCP должны быть универсальные уникальные имена, поэтому воспользуемся предустановленной библиотекой uuid для создания такого рода ID:
9. Как только корзина готова, загружаем в нее файл из среды Colab:
По завершении скачивания файл отображается на панели менеджера файлов в Colab в указанном месте.
Обращение к AWS S3 из Google Colab
Для доступа к S3 из Colab потребуется создать аккаунт AWS, настроить IAM, а также сгенерировать ключ доступа и секретный ключ доступа. Необходимо также установить библиотеку awscli в среду Colab:
1. Устанавливаем библиотеку awscli:
2. После установки запускаем настройку AWS командой aws configure :
3. Вводим access_key и secret_access_key в текстовое окно и нажимаем Enter:
Теперь можно скачивать любые файлы из S3:
filepath_on_s3 позволяет указать один файл или подобрать несколько файлов по шаблону.
Вам придет уведомление о завершении скачивания, после чего файлы будут доступны в заданном месте для дальнейшего использования.
Для загрузки файла просто поменяйте местами аргументы источника и назначения:
file_to_upload позволяет указать один файл или подобрать несколько файлов по шаблону.
Вы получите уведомление об окончании загрузки, и загруженные файлы будут доступны в корзине S3 в заданном каталоге: https://s3.console.aws.amazon.com/s3/buckets/
Обращение к датасетам Kaggle из Google Colab
Для скачивания датасетов из Kaggle требуется наличие аккаунта и API-токена.
- Для создания API-токена заходим в My Account, после чего — Create New API Token.
- Открываем файл kaggle.json и копируем его содержимое в виде < "username":"########", "key":"################################" >.
- Выполняем следующие команды в Colab:
4. После создания файла kaggle.json в Colab и установки библиотеки Kaggle приступаем к поиску датасета с помощью следующей команды:
5. Скачиваем нужный датасет с помощью команды:
Датасет будет загружен и доступен по указанному пути (в данном случае /content/kaggle/ ).
Обращение к базам данных MySQL из Google Colab
1. Для работы с реляционными базами данных необходимо импортировать предустановленную библиотеку sqlalchemy.
2. Вводим данные для подключения и создаем движок:
3. Создаем SQL-запрос и загружаем его результаты в датафрейм с помощью pd.read_sql_query() :
Ограничения Google Colab при работе с файлами
При работе с Colab важно помнить о том, что доступ к загружаемым файл ограничен по времени. Colab — это временная среда, в которой тайм-аут простоя составляет 90 минут, а абсолютный тайм-аут — 12 часов. Это значит, что отключение среды выполнения происходит в случае 90 минутного простоя или 12-ти часового использования. Такое отключение приводит к потери всех переменных, состояний, установленных пакетов и файлов, вследствие чего при повторном подключении вас ждет встреча с абсолютно новой и чистой средой.
Кроме того, дисковое пространство Colab ограничено 108 Гб, только 77 Гб из которых доступны пользователю. Этого объема достаточно для решения большинства задач, но вот при работе с крупными датасетами, например изображениями или видео, данное обстоятельство нельзя упускать из внимания.
Заключение
Google Colab — превосходный инструмент для тех, кто стремится обуздать мощь высокопроизводительных вычислительных ресурсов, таких как GPU, без оглядки на их стоимость.
В данной статье мы рассмотрели большинство способов, благодаря которым вы сможете максимально продуктивно работать с Google Colab, читая внешние файлы или данные в Google Colab и производя обратную запись из нее в эти внешние источники данных.
В зависимости от сценария использования или архитектуры данных вы можете запросто применять вышеописанные методы для подключения источника данных напрямую к Colab и приступать к программированию.
import local file to google colab
I don’t understand how colab works with directories, I created a notebook, and colab put it in /Google Drive/Colab Notebooks.
Now I need to import a file (data.py) where I have a bunch of functions I need. Intuition tells me to put the file in that same directory and import it with:
but apparently that’s not the way.
I also tried adding the directory to the set of paths but I am specifying the directory incorrectly..
Can anyone help with this?
Thanks in advance!
![]()
6 Answers 6
Colab notebooks are stored on Google Drive. But it is run on another virtual machine. So, you need to copy your data.py there too. Do this to upload data.py through Colab.
![]()
Now google is officially providing support for accessing and working with Gdrive at ease.
You can use the below code to mount your drive to Colab:
![]()
To easily upload a local file you can use the new Google Colab feature:
- click on right arrow on the left of your screen (below the Google Colab logo)

- select Files tab
- click Upload button
It will open a popup to choose file to upload from your local filesystem.
To upload Local files from system to collab storage/directory.

![]()
So, here is how I finally solved this. I have to point out however, that in my case I had to work with several files and proprietary modules that were changing all the time.
The best solution I found to do this was to use a FUSE wrapper to «link» colab to my google account. I used this particular tool:
There is an example of how to set up your environment there, but here is how I did it:
At this point you’ll have installed the wrapper and the code above will generate a couple of links for you to authorize access to your google drive account.
The you have to create a folder in the colab file system (remember this is not persistent, as far as I know. ) and mount your drive there:
the !ls command will print the directory contents so you can check it works, and that’s it. You now have all the files you need and you can make changes to them with no further complications. Remember that you may need to restar the kernel to update the imports and variables.
How to Deal With Files in Google Colab: Everything You Need to Know
Google Colaboratory is a free Jupyter notebook environment that runs on Google’s cloud servers, letting the user leverage backend hardware like GPUs and TPUs. This lets you do everything you can in a Jupyter notebook hosted in your local machine, without requiring the installations and setup for hosting a notebook in your local machine.
Colab comes with (almost) all the setup you need to start coding, but what it doesn’t have out of the box is your datasets! How do you access your data from within Colab?
In this article we will talk about:
- How to load data to Colab from a multitude of data sources
- How to write back to those data sources from within Colab
- Limitations of Google Colab while working with external files
Directory and file operations in Google Colab
Since Colab lets you do everything which you can in a locally hosted Jupyter notebook, you can also use shell commands like ls, dir, pwd, cd, cat, echo , et cetera using line-magic (%) or bash (!).
To browse the directory structure, you can use the file-explorer pane on the left.

How to upload files to and download files from Google Colab
Since a Colab notebook is hosted on Google’s cloud servers, there’s no direct access to files on your local drive (unlike a notebook hosted on your machine) or any other environment by default.
However, Colab provides various options to connect to almost any data source you can imagine. Let us see how.
Accessing GitHub from Google Colab
You can either clone an entire GitHub repository to your Colab environment or access individual files from their raw link.
Clone a GitHub repository
You can clone a GitHub repository into your Colab environment in the same way as you would in your local machine, using git clone . Once the repository is cloned, refresh the file-explorer to browse through its contents.
Then you can simply read the files as you would in your local machine.

Load individual files directly from GitHub
In case you just have to work with a few files rather than the entire repository, you can load them directly from GitHub without needing to clone the repository to Colab.
- click on the file in the repository,
- click on View Raw,
- copy the URL of the raw file,
- use this URL as the location of your file.
Accessing Local File System to Google Colab
You can read from or write to your local file system either using the file-explorer, or Python code:
Access local files through the file-explorer
Uploading files from local file system through file-explorer
You can either use the upload option at the top of the file-explorer pane to upload any file(s) from your local file system to Colab in the present working directory.
To upload files directly to a subdirectory you need to:
1. Click on the three dots visible when you hover above the directory
2. Select the “upload” option.

3. Select the file(s) you wish to upload from the “File Upload” dialog window.
4. Wait for the upload to complete. The upload progress is shown at the bottom of the file-explorer pane.

Once the upload is complete, you can read from the file as you would normally.

Downloading files to local file system through file-explorer
Click on the three dots which are visible while hovering above the filename, and select the “download” option.

Accessing local file system using Python code
This step requires you to first import the files module from the google.colab library :
Uploading files from local file system using Python code
You use the upload method of the files object:
Running this opens the File Upload dialog window:

Select the file(s) you wish to upload, and then wait for the upload to complete. The upload progress is displayed:

The uploaded object is a dictionary having the filename and content as it’s key-value pairs:

Once the upload is complete, you can either read it as any other file from colab:
Or read it directly from the uploaded dict using the io library:
Make sure that the filename matches the name of the file you wish to load.
Downloading files from Colab to local file system using Python code:
The download method of the files object can be used to download any file from colab to your local drive. The download progress is displayed, and once the download completes, you can choose where to save it in your local machine.

Accessing Google Drive from Google Colab
You can use the drive module from google.colab to mount your entire Google Drive to Colab by:
1. Executing the below code which will provide you with an authentication link
2. Open the link
3. Choose the Google account whose Drive you want to mount
4. Allow Google Drive Stream access to your Google Account
5. Copy the code displayed, paste it in the text box as shown below, and press Enter

Once the Drive is mounted, you’ll get the message “Mounted at /content/gdrive” , and you’ll be able to browse through the contents of your Drive from the file-explorer pane.

Now you can interact with your Google Drive as if it was a folder in your Colab environment. Any changes to this folder will reflect directly in your Google Drive. You can read the files in your Google Drive as any other file.
You can even write directly to Google Drive from Colab using the usual file/directory operations.
This will create a file in your Google Drive, and will be visible in the file-explorer pane once you refresh it:


Accessing Google Sheets from Google Colab
To access Google Sheets:
1. You need to first authenticate the Google account to be linked with Colab by running the code below:
2. Executing the above code will provide you with an authentication link. Open the link,
3. Choose the Google account which you want to link,
4. Allow Google Cloud SDK to access your Google Account,
5. Finally copy the code displayed and paste it in the text box shown, and hit Enter.

To interact with Google Sheets, you need to import the preinstalled gspread library. And to authorize gspread access to your Google account, you need the GoogleCredentials method from the preinstalled oauth2client.client library:
Once the above code is run, an Application Default Credentials (ADC) JSON file will be created in the present working directory. This contains the credentials used by gspread to access your Google account.

Once this is done, you can now create or load Google sheets directly from your Colab environment.
Creating/updating a Google Sheet in Colab
1. Use the gc object’s create method to create a workbook:
2. Once the workbook is created, you can view it in sheets.google.com.

3. To write values to the workbook, first open a worksheet:
4. Then select the cell(s) you want to write to:

5. This creates a list of cells with their index (R1C1) and value (currently blank). You can modify the individual cells by updating their value attribute:

6. To update these cells in the worksheet, use the update_cells method:

7. The changes will now be reflected in your Google Sheet.

Downloading data from a Google Sheet
1. Use the gc object’s open method to open a workbook:
2. Then read all the rows of a specific worksheet by using the get_all_values method:

3. To load these to a dataframe, you can use the DataFrame object’s from_record method:

Accessing Google Cloud Storage (GCS) from Google Colab
You need to have a Google Cloud Project (GCP) to use GCS. You can create and access your GCS buckets in Colab via the preinstalled gsutil command-line utility.
1. First specify your project ID:
2. To access GCS, you’ve to authenticate your Google account:
3. Executing the above code will provide you with an authentication link. Open the link,
4. Choose the Google account which you want to link,
5. Allow Google Cloud SDK to access your Google Account,
6. Finally copy the code displayed and paste it in the text box shown, and hit Enter.

7. Then you configure gsutil to use your project:
8. You can make a bucket using the make bucket ( mb ) command. GCP buckets must have a universally unique name, so use the preinstalled uuid library to generate a Universally Unique ID:
9. Once the bucket is created, you can upload a file from your colab environment to it:
10. Once the upload has finished, the file will be visible in the GCS browser for your project: https://console.cloud.google.com/storage/browser?project=<project_id>
Once the download has finished, the file will be visible in the Colab file-explorer pane in the download location specified.
Accessing AWS S3 from Google Colab
You need to have an AWS account, configure IAM, and generate your access key and secret access key to be able to access S3 from Colab. You also need to install the awscli library to your colab environment:
1. Install the awscli library
2. Once installed, configure AWS by running aws configure :
- Enter your access_key and secret_access_key in the text boxes, and press enter.
Then you can download any file from S3:
filepath_on_s3 can point to a single file, or match multiple files using a pattern.
You will be notified once the download is complete, and the downloaded file(s) will be available in the location you specified to be used as you wish.
To upload a file, just reverse the source and destination arguments:
file_to_upload can point to a single file, or match multiple files using a pattern.
You will be notified once the upload is complete, and the uploaded file(s) will be available in your S3 bucket in the folder specified: https://s3.console.aws.amazon.com/s3/buckets/
Accessing Kaggle datasets from Google Colab
To download datasets from Kaggle, you first need a Kaggle account and an API token.
1. To generate your API token, go to “My Account”, then “Create New API Token”.
2. Open the kaggle.json file, and copy its contents. It should be in the form of < "username":"########", "key":"################################" >.
3. Then run the below commands in Colab:
4. Once the kaggle.json file has been created in Colab, and the Kaggle library has been installed, you can search for a dataset using
5. And then download the dataset using
The dataset will be downloaded and will be available in the path specified ( /content/kaggle/ in this case).
Accessing MySQL databases from Google Colab
1. You need to import the preinstalled sqlalchemy library to work with relational databases:
2. Enter the connection details and create the engine:
3. Finally, just create the SQL query, and load the query results to a dataframe using pd.read_sql_query():
Limitations of Google Colab while working with Files
One important caveat to remember while using Colab is that the files you upload to it won’t be available forever. Colab is a temporary environment with an idle timeout of 90 minutes and an absolute timeout of 12 hours. This means that the runtime will disconnect if it has remained idle for 90 minutes, or if it has been in use for 12 hours. On disconnection, you lose all your variables, states, installed packages, and files and will be connected to an entirely new and clean environment on reconnecting.
Also, Colab has a disk space limitation of 108 GB, of which only 77 GB is available to the user. While this should be enough for most tasks, keep this in mind while working with larger datasets like image or video data.
Conclusion
Google Colab is a great tool for individuals who want to harness the power of high-end computing resources like GPUs, without being restricted by their price.
In this article, we have gone through most of the ways you can supercharge your Google Colab experience by reading external files or data in Google Colab and writing from Google Colab to those external data sources.
Depending on your use-case, or how your data architecture is set-up, you can easily apply the above-mentioned methods to connect your data source directly to Colab, and start coding!