How to append to a file using PyGithub?

Question:

I want to append to an already existing .txt file using PyGithub in Python.
I have tried this code:

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

but this code deletes the old data and only stores this data i.e. "Text I wanna store" only.

I want to store this data at the end of the previously stored data like
"Previous Data Text I wanna store"

Asked By: Varun Singh

||

Answers:

Your code is above is already good, you simply need to take the original Content of the File, and append new one with a + operator or an f-string

Here is an example

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")
Answered By: urwolfiii

.decoded_content.decode() Return file content

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")
Answered By: Roshan Yadav
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.