XIN ZOU
XIN ZOU

Reputation: 13

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.

Upvotes: 1

Views: 2294

Answers (2)

Iamblichus
Iamblichus

Reputation: 19309

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

Upvotes: 3

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 116918

Please note i am not a python developer this code is a wild guess on my part you will need to fix it.

The Files.copy has a parameter called name which you can send with the request. I am not sure how the optional parameters are sent with the python libray. The only issue i see with this is that you will need to do a file.get first so that you have the current name of the file that you can use to pass to this method.

request = service.files().copy(fileId=original_file_id);
request.Name =  'original file name + current date';
response = request.execute();

Upvotes: 0

Related Questions