Skip to content

Instantly share code, notes, and snippets.

@amzon-ex
Last active August 27, 2022 17:30
Show Gist options
  • Save amzon-ex/03243f0c8e8bc2fdd2e9d01931c5ea49 to your computer and use it in GitHub Desktop.
Save amzon-ex/03243f0c8e8bc2fdd2e9d01931c5ea49 to your computer and use it in GitHub Desktop.
A quick script to move Google Docs files from the root of your Drive to a dedicated folder.
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
# Authentication procedure
gauth = GoogleAuth()
# Try to load saved client credentials
gauth.LoadCredentialsFile("mycreds.txt")
if gauth.credentials is None:
# Authenticate if they're not there
# Set access-type to offline to obtain refresh token
gauth.GetFlow()
gauth.flow.params.update({'access_type': 'offline'})
gauth.flow.params.update({'approval_prompt': 'force'})
gauth.LocalWebserverAuth()
elif gauth.access_token_expired:
# Refresh them if expired
gauth.Refresh()
else:
# Initialize the saved creds
gauth.Authorize()
# Save the current credentials to a file
gauth.SaveCredentialsFile("mycreds.txt")
drive = GoogleDrive(gauth)
# Retrieve list of documents
_f = drive.ListFile({'q': "'{0}' in parents and trashed=false".format('root')}).GetList()
_docs = []
dir_exists = False
for f in _f:
if(f['mimeType'] == 'application/vnd.google-apps.document'):
_docs.append(f)
if(f['title'] == 'Google Docs' and f['mimeType'] == 'application/vnd.google-apps.folder'):
dir_exists = True
dest_folder_id = f['id']
# Create directory if it doesn't exist
if(dir_exists):
print("Directory found.")
else:
print("Directory not found! Creating...")
folder_id = 'root'
file_metadata = {
'title': 'Google Docs',
'parents': [folder_id],
'mimeType': 'application/vnd.google-apps.folder'
}
folder = drive.CreateFile(file_metadata)
folder.Upload()
dest_folder_id = folder['id']
# List the docs
print(f"{len(_docs)} Google Docs found.")
for doc in _docs:
print(doc['title'])
# Shift files upon confirmation
shift_conf = input('\nShift these files to the default folder? [y/]: ')
if(shift_conf == 'y'):
# Shift these docs to the default Google Docs folder
for doc in _docs:
doc['parents'] = [{"kind": "drive#parentReference", "id": dest_folder_id}]
doc.Upload()
print("All files shifted. Exiting.")
else:
print("No action taken! Aborting.")
@amzon-ex
Copy link
Author

Requirements

This uses PyDrive. You'd need to install that.

One would need the client_secrets.json file to run this script. This can be obtained from the Google API Console. Place this in the same directory as the script. An authentication will be initiated the first time you run the script, and the credentials obtained will be stored for future use.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment