how to upload files and folders with pygithub 1

how to upload files and folders with pygithub

from github import Github
g = Github("username", "password")

repo = g.get_user().get_repo(GITHUB_REPO)
all_files = []
contents = repo.get_contents("")
while contents:
    file_content = contents.pop(0)
    if file_content.type == "dir":
        file = file_content

with open('/tmp/file.txt', 'r') as file:
    content =

# Upload to github
git_prefix = 'folder1/'
git_file = git_prefix + 'file.txt'
if git_file in all_files:
    contents = repo.get_contents(git_file)
    repo.update_file(contents.path, "committing files", content, contents.sha, branch="master")
    print(git_file + ' UPDATED')
    repo.create_file(git_file, "committing files", content, branch="master")
    print(git_file + ' CREATED')

Here is what the above code is Doing:
1. Authenticating to github
2. Getting a list of all files in the repo
3. Reading the file we want to upload
4. Checking if the file exists in the repo
5. If it exists, update it
6. If it doesn’t exist, create it

Similar Posts