2016-11-21 26 views
0

pythonのgoogleapiclientモジュールでファイルを明示的に移動することはできますか?しかし、これは、GoogleドライブAPIを使用してファイルを移動する

def move_file(service, filename, init_drive_path, drive_path, copy=False): 
    """Moves a file in Google Drive from one location to another. 

    service: Drive API service instance. 
    filename (string): full name of file on drive 
    init_drive_path (string): initial file location on Drive 
    drive_path (string): the file path to move the file in on Drive 
    copy (boolean): file should be saved in both locations 

    Returns nothing. 
    """ 

は現在、私は、目的の場所にファイルを手動でダウンロードして、これを実行して、再アップロードされています:私は、ファイル、元のパスと宛先パスを考えると、次の関数を作成したいですとにかく大きなファイルには実用的ではなく、回避策のように思えます。

Here's the documentation google-drive-apiで利用できる方法については、あなただけのファイルとフォルダのIDを取得し、更新方法を使用する必要が

答えて

0

Found it here.:以下


EDITを参照してくださいソリューション。古いフォルダ(複数可)内のファイルのコピーを残しておきたい場合はremove_parentsパラメータを除外することができる

file_id = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ' 
folder_id = '0BwwA4oUTeiV1TGRPeTVjaWRDY1E' 
# Retrieve the existing parents to remove 
file = drive_service.files().get(fileId=file_id, 
           fields='parents').execute(); 
previous_parents = ",".join(file.get('parents')) 
# Move the file to the new folder 
file = drive_service.files().update(fileId=file_id, 
            addParents=folder_id, 
            removeParents=previous_parents, 
            fields='id, parents').execute() 

になりますので、私の元の関数(私は私の基本的なヘルパー関数の_getFileIdと_getFolderIdが含まれていない注意してください)次のようなもの:

def move_file(service, filename, init_drive_path, drive_path, copy=False): 
     """Moves a file in Google Drive from one location to another. 

     service: Drive API service instance. 
     'filename' (string): file path on local machine, or a bytestream 
     to use as a file. 
     'init_drive_path' (string): the file path the file was initially in on Google 
     Drive (in <folder>/<folder>/<folder> format). 
     'drive_path' (string): the file path to move the file in on Google 
     Drive (in <folder>/<folder>/<folder> format). 
     'copy' (boolean): file should be saved in both locations 

     Returns nothing. 
     """ 
    file_id = _getFileId(service, filename, init_drive_path) 
    folder_id = _getFolderId(service, drive_path) 

    if not file_id or not folder_id: 
     raise Exception('Did not find file specefied: {}/{}'.format(init_drive_path, filename)) 

    file = service.files().get(fileId=file_id, 
            fields='parents').execute() 
    previous_parents = ",".join(file.get('parents')) 
    if copy: 
     previous_parents = '' 

    file = service.files().update(fileId=file_id, 
             addParents=folder_id, 
             removeParents=previous_parents, 
             fields='id, parents').execute() 
関連する問題