Python: Extract file information from shared drive with Google Drive API

Contents

A memo for extracting a list of files from a specified shared drive directory using the Google Drive API

code

OK if you change the argument of the same function as Python Quickstart

import pickle
import os.path

from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from typing import Final
from typing import List

SCOPES: Final[List] = [
    'https://www.googleapis.com/auth/drive.metadata.readonly'
]
SHARED_DRIVE_ID: Final[str] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
DIRECTORY_ID: Final[str] = "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"
FILENAME: Final[str] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"


def get_credentials(scopes: List):
    credentials = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            credentials = pickle.load(token)
    if not credentials or not credentials.valid:
        if credentials and credentials.expired and credentials.refresh_token:
            credentials.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', scopes)
            credentials = flow.run_local_server(port=0)
        with open('token.pickle', 'wb') as token:
            pickle.dump(credentials, token)
    return credentials


def directory_files(filename: str, directory_id: str,
                    pages_max: int = 10) -> List:
    """
Returns an array of the results of searching by file name under the target directory
    :param filename:file name
    :param directory_id:Directory ID
    :param pages_max:Maximum number of page searches
    :return:File list
    """
    credentials = get_credentials(SCOPES)
    service = build("drive", "v3", credentials=credentials)
    items: List = []
    page = 0
    while True:
        page += 1
        if page == pages_max:
            break
        results = service.files().list(
            corpora="drive",
            driveId=SHARED_DRIVE_ID,
            includeItemsFromAllDrives=True,
            includeTeamDriveItems=True,
            q=f"'{directory_id}' in parents and "
              f"name = '{filename}' and "
              "trashed = false",
            supportsAllDrives=True,
            pageSize=10,
            fields="nextPageToken, files(id, name)").execute()
        items += results.get("files", [])

        page_token = results.get('nextPageToken', None)
        if page_token is None:
            break
    return items

items = drive_util.directory_files(
    filename=FILENAME,
    directory_id=DIRECTORY_ID)
for item in items:
    print(f"{item['id']} : {item['name']}")

reference

https://developers.google.com/drive/api/v3/reference/files/list https://developers.google.com/drive/api/v3/search-files

Recommended Posts

Python: Extract file information from shared drive with Google Drive API
Collecting information from Twitter with Python (Twitter API)
Access Google Drive with Python
Google Drive Api Tips (Python)
Upload JPG file using Google Drive API in Python
Make a copy of a Google Drive file from Python
Extract the xz file with python
Extract template of EML file saved from Thunderbird with python3.7
[python] Read information with Redmine API
Use Google Analytics API from Python
Use Google Cloud Vision API from Python
[Python] Get Python package information with PyPI API
Upload images to Google Drive with Python
Extract lines that match the conditions from a text file with python
Collecting information from Twitter with Python (Environment construction)
Csv output from Google search with [Python]! 【Easy】
Extract text from PowerPoint with Python! (Compatible with tables)
Upload files to Google Drive with Lambda (Python)
Extract zip with Python (Japanese file name support)
Wav file generation from numeric text with python
Read line by line from a file with Python
Extract data from a web page with Python
Data acquisition from analytics API with Google API Client for python Part 2 Web application
Google Drive file move
Drive WebDriver with python
[GCP] [Python] Deploy API serverless with Google Cloud Functions!
Google Drive API Set File Permission (Set permissions on Google Drive files)
Collecting information from Twitter with Python (morphological analysis with MeCab)
Get schedule from Garoon SOAP API with Python + Zeep
Read QR code from image file with Python (Mac)
[Python] Get user information and article information with Qiita API
Speech file recognition by Google Speech API v2 using Python
Extract the band information of raster data with python
YOLP Get map information XML file with Yahoo! Static Map API
Use Twitter API with Python
How to extract any appointment in Google Calendar with Python
Information obtained from tweet_id (Python)
Draw netCDF file with python
Study Python with Google Colaboratory
Get information with zabbix api
Web API with Python + Falcon
Play RocketChat with API / Python
Call the API with python3.
Mount google drive with google-drive-ocamlfuse
Collecting information from Twitter with Python (MySQL and Python work together)
Use subsonic API with python3
With skype, notify with skype from python!
Download csv file with python
Issue reverse geocoding in Japanese with Python Google Maps API
Use e-Stat API from Python
Get Alembic information with Python
Play with YouTube Data API v3 using Google API Python Client
Try to extract a character string from an image with Python3
How to connect to Cloud Firestore from Google Cloud Functions with python code
Read a file in Python with a relative path from the program
[python] Extract text from pdf and read characters aloud with Open-Jtalk
Try to display google map and geospatial information authority map with python
Get US stock price from Python with Web API with Raspberry Pi
Regularly upload files to Google Drive using the Google Drive API in Python
Extract database tables with CSV [ODBC connection from R and python]
Execute Python script from batch file