LoginSignup
14
17

More than 5 years have passed since last update.

PythonからGoogleDriveのファイルのcopyを作成する

Last updated at Posted at 2016-08-12

はじめに

所々の事情により、GoogleDrive上のファイルを自動的に複製する必要が出てきたので、その方法を調べたメモです。

Version

  • Python 3.5.x
  • google-api-python-client==1.5.1
  • oauth2client==3.0.0
  • httplib2==0.9.2

方法

準備: Google Drive API の有効化

http://wwld.jp/2015/11/07/spreadsheet-api.html
で紹介されている通り、Drive APIを有効化する必要がありますので有効化します。

準備: 認証用JSONの取得

Google Drive APIを使うので、認証情報が必要です。
認証情報の取得方法は、時期によって少しずつ変わっているようですが、
前述のサイト 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',  # 新しいファイルのファイル名. 省略も可能
    'parents': ['0Bxxxx-abcdefghijklmnopqrstu'],  # Copy先のFolder ID. 省略も可能
}

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

出力例

{
  'kind': 'drive#file', 
  'mimeType': 'application/vnd.google-apps.spreadsheet', 
  'name': 'new_data', 
  'id': '1zzzzzzzzzzz-xxxxxxxxxxxxxx-xxxxxxxxx'
}

さいごに

できると信じているし、できてしまえば簡単なんですが、方法を探すのに苦労しますね。。

14
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
17