如何使用PyGithub更新文件?

Abh*_*mar 3 python pygithub

我想知道我应该调用哪个方法(以及在哪个对象上)以及如何调用该方法(必需的参数及其含义).

Ser*_*hko 7

import github

g = github.Github(token)
# or  g = github.Github(login, password)

repo = g.get_user().get_repo("repo_name")
file = repo.get_file_contents("/your_file.txt")

# update
repo.update_file("/your_file.txt", "your_commit_message", "your_new_file_content", file.sha)
Run Code Online (Sandbox Code Playgroud)

如果您正在使用令牌,那么您应该至少具有令牌的repo范围来执行此操作. https://developer.github.com/v3/oauth/#scopes

请参阅: https ://developer.github.com/v3/repos/contents/https://github.com/PyGithub/PyGithub


Mix*_*nge 6

截至 2021 年,PyGithub API 已发生更改,并且有一个示例说明如何执行此操作:https://pygithub.readthedocs.io/en/latest/examples/Repository.html#update-a-file-in-the-repository

repo = g.get_repo("PyGithub/PyGithub")
contents = repo.get_contents("test.txt", ref="test")
repo.update_file(contents.path, "more tests", "more tests", contents.sha, branch="test")
# {'commit': Commit(sha="b06e05400afd6baee13fff74e38553d135dca7dc"), 'content': ContentFile(path="test.txt")}
Run Code Online (Sandbox Code Playgroud)

对于.update_file,第一个字符串是消息,第二个字符串是文件的新内容。API 说明如下:

update_file(path, message, content, sha, branch=NotSet, committer=NotSet, author=NotSet)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你。请注意,唯一的实际区别似乎是“get_file_contents”→“get_contents”。 (2认同)