簡體   English   中英

如何使用帶有 Python 的 ID 獲取 Google Drive 上文件的 url

[英]How to get the url of a file on Google Drive using its ID with Python

在下面的代碼中,我得到了 Google Drive 上 csv 文件的文件 ID。 現在,我想將文件內容直接存儲在 pandas 框架中,而不是下載 csv 文件然后提取數據(如代碼所示)。

import io
import os.path
import pandas as pd

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload


# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/drive.readonly']

# Login to Google Drive
def login():

    creds = None
    # The file token.json 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.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)

    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        print ("Login to your to your Google Drive account which holds/shares the file database")
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                './src/credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    # Return service
    service = build('drive', 'v3', credentials=creds)
    
    return service


# Download files from Google Drive
def downloadFile(file_name):

    # Authenticate
    service = login()

    # Search file by name
    response = service.files().list(q=f"name='{file_name}'", spaces='drive', fields='nextPageToken, files(id, name)').execute()
    for file in response.get('files', []):
        file_id = file.get('id')

    # Download file file if it exists
    if ("file_id" in locals()):
        request = service.files().get_media(fileId=file_id)
        fh = io.FileIO(f"./data/{file_name}.csv", "wb")
        downloader = MediaIoBaseDownload(fh, request)
        print (f"Downloading {file_name}.csv")
    else:
        print (f"\033[1;31m Warning: Can't download >> {file_name} << because it is missing!!!\033[0;0m")

    return


downloadFile("NameOfFile")

有什么辦法可以做到這一點? 非常感謝你的幫助

The problem is to be able to do that I need the file's URL but I'm not able to retrieve it. ,我認為您的文件可能是 Google 電子表格。 當文件是 Google 電子表格時, webContentLink不包含在檢索到的元數據中。

如果我對你的情況的理解是正確的,那么下面的修改呢?

修改后的腳本:

從:

file_id = file.get('id')

# !!! Here, I would like to get the URL of the file and download it to a pandas data frame !!!
file_url = file.get("webContentLink")

至:

file_id = file.get('id')
file_url = file.get("webContentLink")
if not file_url:
    request = service.files().export_media(fileId=file_id, mimeType='text/csv')
    fh = io.BytesIO()
    downloader = MediaIoBaseDownload(fh, request)
    done = False
    while done is False:
        status, done = downloader.next_chunk()
        print("Download %d%%" % int(status.progress() * 100))
    fh.seek(0)
    df = pd.read_csv(fh)
    print(df)
  • 在此修改中,使用 Drive API 將 Google 電子表格導出為 CSV 數據,並將導出的數據放入 dataframe。
  • 在此修改中,請添加import iofrom googleapiclient.http import MediaIoBaseDownload

筆記:

  • 在這種情況下,使用 Drive API 將 Google 電子表格導出為 CSV 數據。 所以請包括https://www.googleapis.com/auth/drive.readonlyhttps://www.googleapis.com/auth/drive的 scope 當您的 scope 僅為https://www.googleapis.com/auth/drive.metadata.readonly時,會發生錯誤。 請注意這一點。

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM