【问题标题】:How to append to a file using PyGithub?如何使用 PyGithub 附加到文件?
【发布时间】:2022-10-24 00:44:08
【问题描述】:

我想在 Python 中使用 PyGithub 附加到一个已经存在的 .txt 文件。 我试过这段代码:

git = Github(TOKEN)
repo = git.get_repo("Repository")
file = repo.get_contents("Textfile.txt", ref="Ref")

repo.update_file(file.path, "test", "Text I wanna store", file.sha, branch="Ref")

但此代码删除旧数据并仅存储此数据,即“我想存储的文本”。

我想将此数据存储在先前存储的数据的末尾,例如 “我要存储的以前的数据文本”

【问题讨论】:

  • 下载文件,追加数据,上传新的...
  • 我现在正在使用这种方式,但没有更好的方法来做到这一点。或者库中的任何内置函数可以做到这一点?

标签: python file github pygithub


【解决方案1】:

您上面的代码已经很好了,您只需要获取文件的原始内容,并使用 + 运算符或 f-string 附加新内容

这是一个例子

git = Github(TOKEN)
repo = git.get_repo("Repository")
file = repo.get_contents("Textfile.txt", ref="Ref")
new_data = input("Text you want to add")
update_file(file.path, "NEW COMMIT", f"{file} {new_data}", file.sha,branch="Ref")

【讨论】:

  • 我现在已经这样做了,但是没有更好的方法或库中的内置函数可以这样做
  • @VarunSingh 不,没有,这可能是最快的方法,我阅读了文档,这是最简单和最好的解决方案。
【解决方案2】:

.decoded_content.decode()返回文件内容

git = Github(TOKEN)
repo = git.get_repo("Repository")
file = repo.get_contents("Textfile.txt", ref="Ref")

repo.update_file(file.path, "test", f"{file.decoded_content.decode()} Text I wanna store ", file.sha, branch="Ref")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-12
    • 2010-10-07
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 2017-06-26
    • 2015-11-03
    • 2012-04-01
    相关资源
    最近更新 更多