Last active
September 24, 2017 13:29
-
-
Save kmonsoor/dd7217c2f69a2ff72e2e17743f1d2910 to your computer and use it in GitHub Desktop.
Google Drive API : Copy or move a single file to new folder. If you find this useful, as a 👍, give this gist a ⭐️
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def copy_file_to_folder(file_id, new_folder_id, move=False): | |
# acquiring credentials | |
# for credential function, please refer to: https://gist.github.com/kmonsoor/d89c930a8df3060106c04648dc6058b0 | |
try: | |
drive_service = discovery.build('drive', 'v3', credentials = get_credential_service_account()) | |
except Exception as e: | |
print("File copy/move failed due to failed acquire credentials") | |
raise | |
if move: | |
print("Executing 'Move' request") | |
try: | |
# Retrieve the existing parents to remove | |
fetch_res = drive_service.files().get(fileId=file_id, fields='parents').execute(); | |
previous_parents = ",".join(fetch_res.get('parents')) | |
# Move the file to the new folder | |
move_res = drive_service.files().update(fileId=file_id, addParents=new_folder_id, removeParents=previous_parents, fields='id, parents').execute() | |
except Exception as e: | |
print(e) | |
raise | |
else: | |
print("Executing 'Copy' request"); | |
try: | |
move_res = drive_service.files().update(fileId=file_id, addParents=new_folder_id, fields='id, parents').execute() | |
except Exception as e: | |
print(e) | |
raise |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment