You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Python类生成Google Drive嵌套JSON树形文件目录

Solution: Python Class to Generate Nested JSON Tree from Google Drive

Got it, let's put together a clean, encapsulated Python class that interacts with the Google Drive API and outputs the nested folder/file tree structure you specified. Here's everything you need:

Prerequisites

First, make sure you have the required packages installed:

pip install google-api-python-client oauth2client

You'll also need a credentials.json file from the Google Cloud Console (create a project, enable the Google Drive API, create OAuth 2.0 Desktop credentials, and download the file).

Complete Implementation

import json
from googleapiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run_flow

class GoogleDriveTreeGenerator:
    def __init__(self, credentials_path='credentials.json', token_path='token.json'):
        self.SCOPES = ['https://www.googleapis.com/auth/drive.readonly']
        self.CLIENT_SECRET_FILE = credentials_path
        self.TOKEN_FILE = token_path
        self.service = self._authenticate()

    def _authenticate(self):
        """Handle OAuth2 authentication with Google Drive API"""
        storage = Storage(self.TOKEN_FILE)
        credentials = storage.get()

        if not credentials or credentials.invalid:
            flow = OAuth2WebServerFlow(
                client_id=self._get_client_id(),
                client_secret=self._get_client_secret(),
                scope=self.SCOPES,
                redirect_uri='urn:ietf:wg:oauth:2.0:oob'
            )
            credentials = run_flow(flow, storage)
        
        return build('drive', 'v3', credentials=credentials)

    def _get_client_id(self):
        """Extract client ID from credentials.json"""
        with open(self.CLIENT_SECRET_FILE) as f:
            data = json.load(f)
            return data['installed']['client_id']

    def _get_client_secret(self):
        """Extract client secret from credentials.json"""
        with open(self.CLIENT_SECRET_FILE) as f:
            data = json.load(f)
            return data['installed']['client_secret']

    def _get_folder_contents(self, folder_id='root'):
        """Recursively fetch all files and folders under a given folder ID"""
        results = []
        page_token = None

        # Query to get non-trashed items in the target folder
        query = f"'{folder_id}' in parents and trashed=false"
        
        while True:
            response = self.service.files().list(
                q=query,
                spaces='drive',
                fields='nextPageToken, files(id, name, mimeType)',
                pageToken=page_token
            ).execute()

            for file in response.get('files', []):
                node = {
                    'name': file['name'],
                    'id': file['id'],
                    'type': 'folder' if file['mimeType'] == 'application/vnd.google-apps.folder' else 'file'
                }

                # Recursively fetch children if the item is a folder
                if node['type'] == 'folder':
                    node['children'] = self._get_folder_contents(file['id'])
                
                results.append(node)
            
            page_token = response.get('nextPageToken', None)
            if page_token is None:
                break
        
        return results

    def generate_tree(self, root_folder_id='root'):
        """Generate the full nested JSON tree starting from the specified root folder"""
        tree = self._get_folder_contents(root_folder_id)
        return json.dumps(tree, indent=2)

# Example usage
if __name__ == '__main__':
    # Initialize the generator with your credential files
    generator = GoogleDriveTreeGenerator()
    
    # Generate tree from root Drive folder (pass a specific folder ID to target a subfolder)
    tree_json = generator.generate_tree()
    
    # Print the result or save to a file
    print(tree_json)
    # with open('drive_tree.json', 'w') as f:
    #     f.write(tree_json)

Key Details Explained

  • Authentication: The _authenticate method handles the OAuth2 flow, storing a refresh token in token.json so you won't need to re-authenticate every time you run the script.
  • Recursive Traversal: The _get_folder_contents method uses recursion to dive into each folder, fetching its nested files and subfolders. It also handles API pagination to ensure no items are missed.
  • Node Structure: Each node strictly follows your requested format: includes name, id, type (either 'folder' or 'file'), and a children array for folders.
  • Customization: You can target a specific subfolder by passing its ID to the generate_tree() method instead of using the root Drive folder by default.

Notes

  • The script uses the drive.readonly scope, which is the minimum permission needed for this task.
  • Large Drive structures may take a few moments to traverse depending on the number of items.
  • Trashed files/folders are excluded from the tree to keep the output clean.

内容的提问来源于stack exchange,提问作者Soni Pandey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:18:45