Python - 使用 PyGithub 将文件直接上传到 github

标签 python git github

我有一个公共(public)存储库,想使用 python(PyGithub 库)将文件上传到该存储库。
我从 SO 中引用了以下代码:

import base64
from github import Github
from github import InputGitTreeElement

user = "GithubUsername"
password = "*********"
g = Github(user,password)
repo = g.get_user().get_repo('git-test')
file_list = [
    'C:\\Users\jesse\Dropbox\Swell-Forecast\git-test\index.html',
    'C:\\Users\jesse\Dropbox\Swell-Forecast\git-test\margin_table.html'
]

file_names = [
    'index.html',
    'margin_table.html'
]
commit_message = 'python update 2'
master_ref = repo.get_git_ref('heads/master')
master_sha = master_ref.object.sha
base_tree = repo.get_git_tree(master_sha)
element_list = list()
for i, entry in enumerate(file_list):
    with open(entry) as input_file:
        data = input_file.read()
    if entry.endswith('.png'):
        data = base64.b64encode(data)
    element = InputGitTreeElement(file_names[i], '100644', 'blob', data)
    element_list.append(element)
tree = repo.create_git_tree(element_list, base_tree)
parent = repo.get_git_commit(master_sha)
commit = repo.create_git_commit(commit_message, tree, [parent])
master_ref.edit(commit.sha)
但我不想克隆 repo,添加文件然后提交。相反,只需直接上传文件。
是否有任何方法/示例代码可用于直接上传?
例如:
当前 repo :
file1.txt
file2.txt
上传新文件:
file1.txt
file2.txt
myfolder/
        |_ file3.txt
        |_ file4.txt

最佳答案

我为此创建了一小部分代码。它奏效了。在这里分享,让其他人可以从中受益。
示例代码:
此代码将上传文件/替换现有文件。
本地文件路径:/tmp/file.txtGithub 文件夹名称:folder1/

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')
This question也与此有关。

关于Python - 使用 PyGithub 将文件直接上传到 github,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63427607/

相关文章:

python - 解析和处理表格.txt 文件

Python 套接字 - 向服务器发送数据包并等待响应

git - Gerrit 服务器如何拦截提交。寻找技术细节

javascript - 为什么 GitHub 会在我的 jekyll 站点上附加一个 js

python - 在 python 中,是否有最佳实践方法来清理包含需要转义字符的正则表达式搜索字符串?

Python:-给定元组坐标列表,找到最接近指定坐标的坐标(谷歌地图坐标))

git - 如何找到原名已知的重命名文件的新路径?

git - 在 docker 容器中获取代理后面的 git

git - 错误: RPC failed; HTTP 502 curl 22 The requested URL returned error: 502 Bad Gateway fatal

security - Dependabot/Snyk工具,例如Rust和/或Elixir语言