使用 PyGitHub 通过 Python 将文件推送到 GitHub,出现“找不到分支主”错误

问题描述

我正在尝试使用以下代码将 .csv 文件上传到 GitHub:

### THIS PART WOKRS ###
g = Github("My_Access_Key")
repo = g.get_user().get_repo('Tradr')
all_files = []
contents = repo.get_contents("")
while contents:
    file_content = contents.pop(0)
    if file_content.type == "dir":
        contents.extend(repo.get_contents(file_content.path))
    else:
        file = file_content
        all_files.append(str(file).replace('ContentFile(path="','').replace('")',''))
with open('./Data/PriceGrabber/PriceData.csv','r') as file:
    content = file.read()
# Upload to github
git_prefix = 'Tradr/'
git_file = git_prefix + 'PriceData.csv'
### THIS PART WORKS ###

### GET AN ERROR HERE BELOW ###
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')
else:
    repo.create_file(git_file,branch="master")
    print(git_file + ' CREATED')

这是我得到的错误

GithubException: 404 {"message": "Branch master not found","documentation_url": "https://docs.github.com/rest/reference/repos#create-or-update-file-contents"}

我可以使用任何可能更好的方法。搜了一下好像说这可能是认证问题[1]。

[1] https://github.com/octokit/rest.js/issues/560

解决方法

我遇到了同样的问题。 在我通过 branch='main' 更改了 branch='master' 后,它起作用了。

那是因为:https://www.zdnet.com/article/github-to-replace-master-with-main-starting-next-month/

干杯,