首页 > 解决方案 > 无法使用 Google Drive API 在 Drive 中上传某些类型

问题描述

我正在尝试使用以下代码更新驱动器中的一些文件

from apiclient.discovery import build
from apiclient.http import MediaIoBaseDownload, MediaFileUpload
from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
import io
import pandas as pd

PATH_FOLDER = './'

scopes = ['https://www.googleapis.com/auth/drive']

credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scopes)

http_auth = credentials.authorize(Http())
drive = build('drive', 'v3', http=http_auth)

def upload_file(file_name):
    """ This function purpose is to find
    a file in the drive having the same name as the 
    file_name parameter then uploads a new version 
    using the local file having the same name
    param:
    file_name(str) : name of the file to update in drive (also
    name of the local file to use as new version)
    """ 
    files = drive.files().list().execute()['files']
    for file in files:
        if file['name'] == file_name:
            file_id = file['id']
            break
    file_metadata = {
    'name': file_name,
    'mimeType': file['mimeType']
    }
    media = MediaFileUpload(PATH_FOLDER + file_name, mimetype=file['mimeType'], resumable=True)
    drive.files().update(
    fileId=file_id,
    body=file_metadata, 
    media_body=media, 
    ).execute()

当我尝试上传某些文件类型(pkl、csv)时:

upload_file('universe.pkl')
upload_file('list.csv')

代码运行没有任何错误,但我的驱动器中的文件没有更改,而当我对不同类型(xlsx,txt)应用相同的功能时:

upload_file('info.xlsx')
upload_file('test.txt')

它工作正常,我的文件得到更新。有没有人面临同样的问题?如果是这样,解决方案是什么?

谢谢。

标签: pythongoogle-drive-api

解决方案


upload_file函数的以下行中,您对 mime 类型进行了硬编码:

media = MediaFileUpload(PATH_FOLDER + file_name, mimetype='text/csv', resumable=True)

确保您指定的 mime-typefile-metadata等于media


推荐阅读