Created
June 2, 2020 12:56
-
-
Save hfutxqd/ab499b9801186bd37b78c3c21453245b to your computer and use it in GitHub Desktop.
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
from pydrive.auth import GoogleAuth | |
from pydrive.drive import GoogleDrive | |
def get_file_dir_path(drive, file, files_map): | |
if 'parents' in file and len(file['parents']) > 0: | |
if file['parents'][0]['isRoot']: | |
return file['title'] | |
parent_title = get_file_dir_path(drive, files_map[file['parents'][0]['id']], files_map) | |
return parent_title + '/' + file['title'] | |
else: | |
return file['title'] | |
def mkdirs(drive, dirs, parent_id=None): | |
for dir in dirs: | |
if not dir: | |
continue | |
if parent_id: | |
file_metadata = { | |
'title': dir, | |
'parents': [{'id': parent_id}], | |
'mimeType': 'application/vnd.google-apps.folder' | |
} | |
else: | |
file_metadata = { | |
'title': dir, | |
'mimeType': 'application/vnd.google-apps.folder' | |
} | |
file = drive.CreateFile(file_metadata) | |
file.Upload() | |
parent_id = file['id'] | |
return parent_id | |
def copy_file(drive, source_id, parent_id, dest_title): | |
copied_file = {'title': dest_title, 'parents': [{'id': parent_id}]} | |
f = drive.auth.service.files().copy(fileId=source_id, body=copied_file).execute() | |
dest_id = f['id'] | |
dest = drive.CreateFile({'id': dest_id}) | |
dest.FetchMetadata('title') | |
return dest['id'] | |
gauth = GoogleAuth() | |
gauth.LocalWebserverAuth() | |
drive = GoogleDrive(gauth) | |
file_list = drive.ListFile().GetList() | |
files_map = {} | |
with open('test.json', 'w+') as f: | |
import json | |
f.write(json.dumps(file_list, ensure_ascii=False)) | |
for file in file_list: | |
files_map[file['id']] = file | |
for file in file_list: | |
if not file['owners'][0]['isAuthenticatedUser']: | |
dir_path = get_file_dir_path(drive, file, files_map) | |
dir_id = mkdirs(drive, dir_path.split('/')[0:-1]) | |
if file['copyable']: | |
copy_file(drive, file['id'], dir_id, file['title']) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment