python - 无法使用 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')
它工作正常,我的文件得到更新。有没有人面临同样的问题?如果是这样,解决方案是什么?
谢谢。
解决方案
在upload_file
函数的以下行中,您对 mime 类型进行了硬编码:
media = MediaFileUpload(PATH_FOLDER + file_name, mimetype='text/csv', resumable=True)
确保您指定的 mime-typefile-metadata
等于media
推荐阅读
- iis - IIS 上的 Blazor 服务器端应用程序经常断开 WebSocket 连接
- postgresql - Aurora postgres 10.7 的这个插入查询有什么问题?
- ios - 没有 performSegue 的委托不会被调用 Swift 5
- flutter - Flutter:如何在文本字段文本中间插入文本
- django - Django:AttributeError:'str'对象没有属性'objects'
- r - 为列表的因子分配一个随机值 - 0 或 1
- jenkins - 如何在 Jenkins 中为 C# 运行 Selenium 测试
- ios - 如何正确子类 React 本机 webview 以禁用选择时的上下文菜单?
- javascript - 如何使用 vanilla JavaScript 重新启动 CSS 动画?
- asp.net - 引导轮播在 ASP.NET Core 中不起作用