Search code examples
pythongoogle-drive-apigoogle-api-python-client

How to get (and append) content of a text file on Google Drive


This should be super easy, but somehow I cannot figure it out by myself... I want to get content of a txt file from Google Drive Api v3, using (for example) python. According to docs (https://developers.google.com/drive/api/v3/reference/files/get) get method "Gets a file's metadata or content by ID." Here is what I have:

body =  service.files().get(fileId="rGCalhPNeL9HejmmHCJhyt2aBRG40hDhb")
print(body)

but this prints: googleapiclient.http.HttpRequest object at 0x1ed5990 instead of file content. What I am doing wrong?

Second question is: can I append a new line to existing google drive file? I know how to create a new file and update a file (but this overwrites everything what is inside a file). Is there a way I can just add another line to existing text file?

Thanks!


Solution

  • Answer for question 1 :

    How about this modification?

    From :
    body =  service.files().get(fileId="rGCalhPNeL9HejmmHCJhyt2aBRG40hDhb")
    
    To :
    body = service.files().get_media(fileId="rGCalhPNeL9HejmmHCJhyt2aBRG40hDhb").execute()
    

    Answer for question 2 :

    For example, if the file is spreadsheet and slides, there are APIs for adding contents. But in the case of a text file, because there are not such specific APIs, when a new line is added, the following flow is used.

    1. Download contents from the file.
    2. Add the new line to the contents.
    3. Upload the new contents as update to the text file.

    If this answer was not what you want, I'm sorry.