我需要获取 Google Drive 文件夹中所有文件的大小。我没有计算 Google 类型的文件(Google 表格等...)
这是代码
import os
from googleapiclient.discovery import build
# from google.oauth2.credentials import Credentials
from google.oauth2.service_account import Credentials as ServiceAccountCredentials
# Replace with the path to your JSON credentials file
JSON_CREDS_PATH = 'drivedownload-credentials.json'
# Shared folder ID
SHARED_FOLDER_ID = 'XXX-XXXXXXXXXXXXXXXXXXXXXXx'
def get_drive_service():
# Load credentials from JSON file
credentials = None
if os.path.exists(JSON_CREDS_PATH):
credentials = ServiceAccountCredentials.from_service_account_file(
JSON_CREDS_PATH, scopes=['https://www.googleapis.com/auth/drive']
)
else:
print("Credentials JSON file not found.")
# Build the Google Drive API service
if credentials:
service = build('drive', 'v3', credentials=credentials)
return service
def calculate_folder_size(service, folder_id):
total_size = 0
page_token = None
while True:
response = service.files().list(
q=f"'{folder_id}' in parents",
spaces='drive',
fields='files(size), nextPageToken',
pageToken=page_token
).execute()
files = response.get('files', [])
for file in files:
total_size += int(file['size'])
page_token = response.get('nextPageToken', None)
if not page_token:
break
return total_size
def main():
drive_service = get_drive_service()
if drive_service:
folder_size = calculate_folder_size(drive_service, SHARED_FOLDER_ID)
print(f"Total size of files in the shared folder: {folder_size} bytes")
if __name__ == "__main__":
main()
尺寸为零。