繁体   English   中英

Python - pygithub 如果文件存在则更新否则创建

[英]Python - pygithub If file exists then update else create

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

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

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

PyGithub 有可能吗?

我听从了 The Otterlord 的建议,我做到了。 在这里分享我的代码,它可能对某人有帮助。

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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM