Google Colab provides a simple way to write and execute Python code using cloud resources. However, for continuous machine learning, it's essential to keep your code version-controlled and synced with GitHub. This tutorial shows how to upload a folder from Google Colab to GitHub effortlessly.
Prerequisites
- A GitHub account (Sign up here)
- A Google Drive account
- A GitHub repository where you want to upload files
Steps to Upload a Folder from Colab to GitHub
1. Generate a GitHub Token
To push code to GitHub from Colab, you need a Personal Access Token.
- Go to GitHub Tokens
- Click Generate new token (classic)
- Select necessary permissions:
repo
(for full repo access) - Generate and copy the token (you will need it later)
2. Set Up Google Colab for GitHub Upload
Copy and run the following code in a Colab notebook:
# Replace with your details
token = 'your_github_token'
user_name = 'your_github_username'
repo_name = 'your_repository_name'
code_folder = '/content/drive/MyDrive/Colab Notebooks/your_project_folder'
# Mount Google Drive
from google.colab import drive
drive.mount('/content/drive', force_remount=True)
# Check Git version
!git version
# Set up Git configuration
!git config --global user.email "your_email@example.com"
!git config --global user.name "{user_name}"
# Clone GitHub repo
!git clone https://{token}@github.com/{user_name}/{repo_name}.git
# Sync Colab folder with GitHub repo
!rsync -av "{code_folder}/" "/content/{repo_name}"
# Push to GitHub
%cd /content/{repo_name}
!git add .
!git commit -m "Initial commit"
!git remote add origin https://{token}@github.com/{user_name}/{repo_name}.git
!git push -u origin main
Explanation of the Code
- Mounts Google Drive: Allows access to files stored in Google Drive.
- Sets Git Configuration: Defines user details for Git operations.
- Clones the GitHub repository: Ensures the local version is up-to-date.
-
Copies files using
rsync
: Syncs the specified folder from Google Drive to the cloned repo. - Commits and Pushes changes: Updates GitHub with the latest changes.
Why Use This Method?
- Automates code synchronization between Colab and GitHub.
- Allows continuous machine learning workflows.
- Keeps project versions safe and trackable.
Follow Me
- LinkedIn: https://www.linkedin.com/in/shemanto/
- GitHub: http://github.com/shemanto27
Happy coding! 🚀
Top comments (0)