Created
August 23, 2023 01:57
-
-
Save alexjyong/fc80c6f7870c03371dd99a6bd2e42bcb to your computer and use it in GitHub Desktop.
get file list from google drive
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 google.oauth2.credentials import Credentials | |
from googleapiclient.discovery import build | |
ACCESS_TOKEN = 'YOUR_ACCESS_TOKEN_FROM_PLAYGROUND' | |
def bytes_to_human_readable(byte_size): | |
"""Convert bytes to human-readable file sizes.""" | |
for unit in ['B', 'KB', 'MB', 'GB', 'TB']: | |
if byte_size < 1024.0: | |
return f"{byte_size:.2f} {unit}" | |
byte_size /= 1024.0 | |
return f"{byte_size:.2f} PB" | |
def main(): | |
creds = Credentials(token=ACCESS_TOKEN) | |
service = build('drive', 'v3', credentials=creds) | |
# Call the Drive API to get a list of files along with their sizes | |
# Add the query parameter to list only the files you own | |
results = service.files().list( | |
pageSize=1000, | |
fields="nextPageToken, files(id, name, mimeType, size)", | |
q="'me' in owners" | |
).execute() | |
items = results.get('files', []) | |
if not items: | |
print('No files found.') | |
else: | |
# Sort the files by size in descending order | |
sorted_items = sorted(items, key=lambda x: int(x.get('size', 0)), reverse=True) | |
for item in sorted_items: | |
size = item.get('size') | |
if size: | |
print(f"{item['name']} ({bytes_to_human_readable(int(size))})") | |
else: | |
# Check if the file is a Google-native file | |
if 'google-apps' in item.get('mimeType', ''): | |
print(f"{item['name']} (Size not applicable for Google-native files)") | |
else: | |
print(f"{item['name']} (Unknown size)") | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment