Due to some circumstances, it became necessary to automatically duplicate the files on Google Drive, so this is a memo that investigated how to do it.
http://wwld.jp/2015/11/07/spreadsheet-api.html As introduced in, you need to enable the Drive API, so enable it.
Credentials are required as it uses the Google Drive API. The method of obtaining authentication information seems to change little by little depending on the time, I think that it is generally okay to use a method like the above site http://wwld.jp/2015/11/07/spreadsheet-api.html.
SECRET_JSON = '<PATH_TO_SECRET_JSON>'
FILE_ID = '<FILE ID on Google Drive>'
# ---- get credentials
from oauth2client.service_account import ServiceAccountCredentials
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name(SECRET_JSON, scope)
# ---- create Google Drive Service
from apiclient.discovery import build
import httplib2
http = httplib2.Http()
http = credentials.authorize(http)
service = build('drive', 'v3', http=http)
# ---- Copy the file on Google Drive
new_file_body = {
'name': 'new_data', #File name of the new file.Can be omitted
'parents': ['0Bxxxx-abcdefghijklmnopqrstu'], #Folder ID of the copy destination.Can be omitted
}
# ref: https://developers.google.com/resources/api-libraries/documentation/drive/v3/python/latest/drive_v3.files.html#copy
new_file = service.files().copy(
fileId=FILE_ID, body=new_file_body
).execute()
print(new_file)
Output example
{
'kind': 'drive#file',
'mimeType': 'application/vnd.google-apps.spreadsheet',
'name': 'new_data',
'id': '1zzzzzzzzzzz-xxxxxxxxxxxxxx-xxxxxxxxx'
}
I believe I can do it, and once it's done, it's easy, but it's hard to find a way. ..
Recommended Posts