google driver 上传文件等操作

本文介绍如何利用Google Drive API进行文件上传操作,通过Python代码实现文件的上传、下载及管理,具体展示了如何使用OAuth2.0进行身份验证,以及如何使用MediaFileUpload和MediaIoBaseDownload类进行文件的上传和下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

google driver 上传文件等操作

from __future__ import print_function
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 apiclient.http import MediaFileUpload
from googleapiclient.http import MediaIoBaseDownload
import os
import io

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable']
"""Shows basic usage of the Drive v3 API.
Prints the names and ids of the first 10 files the user has access to.
"""
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)

def readfile():
    # Call the Drive v3 API
    results = service.files().list(
         fields="nextPageToken, files(id, name)").execute()
    items = results.get('files', [])

    if not items:
        print('No files found.')
    else:
        print('Files:')
        for item in items:
            print(u'{0} ({1})'.format(item['name'], item['id']))

def insertfile_folder(folder_id,filepath):
    files = os.listdir(filepath)
    for filename in files:
        file_metadata = {
            'name': filename,
            'parents': [folder_id]
        }
        media = MediaFileUpload(os.path.join(filepath, filename),
                                mimetype='text/csv',
                                resumable=True)
        file = service.files().create(body=file_metadata,
                                            media_body=media,
                                            fields='id').execute()
        print('File ID: %s' % file.get('id'))
# readfile()
insertfile_folder('1yxlSET77TYKsI98tEe7IVhoh-RMcS2KU',r'D:\hongkong_data\hkexnews')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值