首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python - pygithub如果文件存在,则更新否则创建

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

Stack Overflow用户
提问于 2020-08-16 18:53:54
回答 1查看 1.2K关注 0票数 0

我正在使用PyGithub库来更新文件。我正面临着这样的问题。一般来说,我们必须选择。我们可以创建一个新文件,或者如果该文件存在,则可以进行更新。

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

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

使用PyGithub可以做到这一点吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-17 14:19:46

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

代码语言:javascript
复制
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')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63435987

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档