sparkandshine sparkandshine - 11 months ago 90
Python Question

How do I push new files to GitHub?

I created a new repository on and then cloned it to my local machine with

git clone

I added 3 new files under the folder

$ tree
├── numerical_analysis
│   └── regression_analysis
│   ├──
│   ├── simple_regression_analysis.png
│   └──

Now, I'd like to upload 3 new files to my GitHub using Python, more specifically, PyGithub. Here is what I have tried:

#!/usr/bin/env python
# *-* coding: utf-8 *-*
from github import Github

def main():
# Step 1: Create a Github instance:
g = Github("usrname", "passwd")
repo = g.get_user().get_repo('mathematics')

# Step 2: Prepare files to upload to GitHub
files = ['mathematics/numerical_analysis/regression_analysis/', 'mathematics/numerical_analysis/regression_analysis/simple_regression_analysis.png']

# Step 3: Make a commit and push
commit_message = 'Add simple regression analysis'

tree = repo.get_git_tree(sha)
repo.create_git_commit(commit_message, tree, [])

if __name__ == '__main__':

I don't know

  • how to get the string

  • how do I make a connection between step 2 and 3, i.e. pushing specific files

Personally, PyGithub documentation is not readable. I am unable to find the right api after searching for long time.

Answer Source

I tried to use the GitHub API to commit multiple files. This page for the Git Data API says that it should be "pretty simple". For the results of that investigation, see this answer.

I recommend using something like GitPython:

from git import Repo

repo_dir = 'mathematics'
repo = Repo(repo_dir)
file_list = [
commit_message = 'Add simple regression analysis'
origin = repo.remote('origin')

Note: This version of the script was run in the parent directory of the repository.