Google 驱动器 API Python - 如何为使用 api 下载的文件设置目的地

Google drive API Python - how to set a destination to files that are downloaded with the api

我正在将文件下载到驱动器中的一个文件夹中,我想将它们也存储在我的 python 脚本所在的同一位置的本地文件夹中,而不是在没有文件夹的情况下将它们保存为 unorderer my当前代码在这里:

import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import io
from googleapiclient.http import MediaIoBaseDownload

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

def main():
 
    creds = None
    # The file token.pickle 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.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)

    # Call the Drive v3 API
    
    # supose that 213fkrjbk324fnvbknfd is the folder id

    query = "'213fkrjbk324fnvbknfd' in parents"
 
    response = service.files().list(q=query,
                                spaces='drive',
                                fields='files(id, name, parents)').execute()
    
    for document in response['files']:
        #file_id = service.files.list()
        request = service.files().get_media(fileId=document['id'])
        fh = io.FileIO('filename.extension', mode='wb')
        downloader = MediaIoBaseDownload(fh, request)
        done = False
        while done is False:
            status, done = downloader.next_chunk()
            print(document['name'])
            print ("Download %d%%." % int(status.progress() * 100))
            print("-------------------------------------------------------------------------------------")

   

if __name__ == '__main__':
    main()
    
    

当我 运行 此代码时,控制台显示下载 100% 字符串,但我无法在我的脚本位置或本地存储的其他位置找到文件。

下载的数据仍然保存在内存中。这会将数据复制到 python 文件所在的文件夹。

while done is False:
    [....]

# This is where it downloads the file
fh.seek(0)
with open('your_filename.pdf', 'wb') as f:
    shutil.copyfileobj(fh, f, length=131072)

如果您遇到问题,我找到了这个答案