![](/img/trans.png)
[英]How to upload csv files to google drive using python drive api
[英]Problem Using Python to Upload Non-Standard Files to Google Drive
我的组织正在将我们的 on-site.network 驱动器转移到 Google 云端硬盘,我希望自动化一些过程。 不是贸易开发人员,但我确实有编程经验。 以前从未与 Python 或 Google API 合作过,但我喜欢挑战。 虽然一路上有点卡住了 - 我让它循环遍历所有文件和目录,我想我什至找到了一种方法来正确地将它带到 map 整个文件系统。 奇怪的是,我认为这是一件很常见的事情,但我还没有找到任何代码可以做到这一点。 如果您知道将整个目录复制到 Google 云端硬盘以便保留所有子目录的方法,请告诉我; 我自己做的,有点乱。 但是,当我运行它时,它适用于某些文件类型,但如果遇到不常见的文件类型(如 txt、docx 或 xlsx),则会因 UnknownFileType 错误而崩溃。 显然,需要传输文件的人将拥有所有类型的文件,所以这根本行不通。 不知道如何解决它。 我认为如果我设置 mimeType 元数据我可以使单个文件工作但如果它在多个文件上运行我不能手动设置 mimeType。 也许有一种不同的方法可以上传可以处理任何类型的文件而无需知道 mimeType? 由于这是我第一次使用 Python 或 Google API,我主要复制了他们网站上的代码以及我在其他位置找到的一些代码,然后对其进行编辑以循环浏览我需要的所有文件。 如果它是一个奇怪的扩展名,上传甚至不会对一个文件起作用。 希望大家能找出问题所在。 这是相关的代码块。
for filename in filenames:
print("Uploading file " + filename + " to " + folnames[i])
file_metadata = {'name': filename,
'parents' : [folids[i]]}
file = service.files().create(body=file_metadata,
media_body=dirpath + "\\" + filename,
fields='id').execute()
print("Upload Complete")
任何帮助表示赞赏。 谢谢!
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
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive']
def main():
"""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)
file_metadata = {'name': 'FILENAME'}
file = service.files().create(body=file_metadata,
media_body='FILEPATH',
fields='id').execute()
print ("File ID: %s" % file.get('id'))
if __name__ == '__main__':
main()
通过使用 MimeTypes 猜测媒体主体的 mimetype 和 MediaFileUpload 使其工作。 感谢大家的帮助和建议。
---
from __future__ import print_function
import pickle
import mimetypes
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive']
def main():
"""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)
mime = mimetypes.MimeTypes().guess_type("FILE")[1]
file_metadata = {'name': 'NAME',
'mimeType': mime}
media = MediaFileUpload('FILE', mimetype = mime)
file = service.files().create(body=file_metadata,
media_body= media,
fields='id').execute()
print ("File ID: %s" % file.get('id'))
if __name__ == '__main__':
main()
---
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.