【问题标题】:Python - pygithub If file exists then update else createPython - pygithub 如果文件存在则更新否则创建
【发布时间】:2020-08-16 10:53:53
【问题描述】:

我正在使用 PyGithub 库来更新文件。我面临一个问题。一般来说,我们必须选择。我们可以创建一个新文件,或者如果文件存在,那么我们可以更新。

文档参考:https://pygithub.readthedocs.io/en/latest/examples/Repository.html#create-a-new-file-in-the-repository

但问题是,如果不存在,我想创建一个新文件。如果存在使用更新选项。

PyGithub 可以做到这一点吗?

【问题讨论】:

标签: python pygithub


【解决方案1】:

我遵循了The Otterlord's 的建议,我已经做到了。在这里分享我的代码,可能对某人有帮助。

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":
        contents.extend(repo.get_contents(file_content.path))
    else:
        file = file_content
        all_files.append(str(file).replace('ContentFile(path="','').replace('")',''))

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

# 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')
else:
    repo.create_file(git_file, "committing files", content, branch="master")
    print(git_file + ' CREATED')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 2016-08-01
    相关资源
    最近更新 更多