Search code examples
pythongoogle-drive-apigoogle-sheets-apigoogle-api-python-clientgspread

How to rename a google spreadsheet via Google Drive API in python?


I'm using Google Drive API in Python to make archiving of my files. However i am having an issue renaming the copy of my original file.

The title of my new file defaults to

'Copy of + original filename'

However I want my new file's name is

'original filename + current date'

I can't find how to change the title configure in the copied code or rename the new file I have copied.

The copy code I used is:

service.files().copy(fileId=original_file_id).execute()

Does anyone know how to rename a file title in Python? Or any alternate method will also be welcome.


Solution

  • I'm unsure how exactly you want the date and the copied file name to be formatted, but you can do the following:

    • Retrieve the name of the original file via Files: get.
    • Copy the file via Files: copy, and retrieve the copied file ID.
    • Build the desired name, using the name of the original file and whatever date you have.
    • Update the copy with the new name, via Files: update.

    Code snippet:

    from datetime import date
    
    def copyFile(service, fileId):
        fileName = service.files().get(fileId=fileId).execute()["name"]
        copyId = service.files().copy(fileId=fileId).execute()["id"]
        currentDate = date.today()
        copyName = "{} | {}".format(fileName, currentDate)
        body = { "name": copyName }
        service.files().update(fileId=copyId, body=body).execute()