Last active
June 6, 2023 23:52
-
-
Save jonathanhle/65ea125f97243f3713f536ce26dca901 to your computer and use it in GitHub Desktop.
Google "Desktop" App Python Script to Delete Specific Files from Google Drive Trash
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 googleapiclient.discovery import build | |
from googleapiclient.errors import HttpError | |
from google_auth_oauthlib.flow import InstalledAppFlow | |
from google.auth.transport.requests import Request | |
import os | |
import pickle | |
# If modifying these SCOPES, delete the file token.pickle. | |
SCOPES = ['https://www.googleapis.com/auth/drive'] | |
def main(): | |
"""Shows basic usage of the Drive v3 API. | |
""" | |
creds = None | |
# The file token.pickle stores the user's access and refresh tokens, and is | |
# created automatically when the authorization flow completes for the first | |
# time. | |
if os.path.exists('token.pickle'): | |
with open('token.pickle', 'rb') as token: | |
creds = pickle.load(token) | |
# If there are no (valid) credentials available, let the user log in. | |
if not creds or not creds.valid: | |
if creds and creds.expired and creds.refresh_token: | |
creds.refresh(Request()) | |
else: | |
flow = InstalledAppFlow.from_client_secrets_file( | |
'credentials.json', SCOPES) | |
auth_url, _ = flow.authorization_url( | |
'https://accounts.google.com/o/oauth2/auth') | |
print('Please go to this URL and authorize the application: ' + auth_url) | |
auth_code = input('Enter the authorization code: ') | |
flow.fetch_token(code=auth_code) | |
creds = flow.credentials | |
# Save the credentials for the next run | |
with open('token.pickle', 'wb') as token: | |
pickle.dump(creds, token) | |
try: | |
service = build('drive', 'v3', credentials=creds) | |
# Call the Drive v3 API to list all files in the trash | |
results = service.files().list(q='trashed = true').execute() | |
items = results.get('files', []) | |
# Iterate over all files | |
for item in items: | |
# If the file's name starts with "signal", delete it | |
if item['name'].startswith('signal'): | |
service.files().delete(fileId=item['id']).execute() | |
print(f'Deleted file: {item["name"]} (ID: {item["id"]})') | |
except HttpError as error: | |
print(f'An error occurred: {error}') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment