gpt4 book ai didi

python - 在谷歌驱动器中创建一个文件夹并将文件上传到其中

转载 作者:太空宇宙 更新时间:2023-11-03 21:22:36 25 4
gpt4 key购买 nike

如何在 Google 云端硬盘中创建文件夹并将文件上传到该文件夹​​中? (在Python中)

我尝试过谷歌教程,但它给了我错误

创建文件夹,无法正常工作,出现“drive_service not Define”等错误

file_metadata = {
'title': 'Files',
'mimeType': 'application/vnd.google-apps.folder'
}
file = drive_service.files().insert(body=file_metadata,
fields='id').execute()
print 'Folder ID: %s' % file.get('id')

使用此代码上传文件并且它正在工作,我如何修改它以将文件上传到文件夹(如果存在),如果不创建并上传。

import json
import requests
headers = {"Authorization": "Bearer Token"}

para = {
"name": "index.jpeg",

}
files = {
'data': ('metadata', json.dumps(para), 'application/json; charset=UTF-8'),
'file': open("./index.jpeg", "rb")
}
r = requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
headers=headers,
files=files
)
print(r.text)

最佳答案

这是我认为您正在寻找的示例(它是一个独立的示例,但我认为您可以将其修改为您自己的现有代码):

from __future__ import print_function
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from httplib2 import Http
from oauth2client import file, client, tools

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

def main():

# Access the Drive service
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('drive', 'v3', http=creds.authorize(Http()))


# Check if folder exists (simply matching by name)
folder_name = "Photos"

folder_id = None
query = "mimeType='application/vnd.google-apps.folder' and trashed=false and name='" + folder_name + "'"
results = service.files().list(
pageSize=1, q=query, fields="files(id, name)").execute()
folders = results.get('files', [])

if folders:
folder_id = folders[0]['id']

# If folder not found, then create it.
else:
file_metadata = {
'name': folder_name,
'mimeType': 'application/vnd.google-apps.folder'
}
folder_file = service.files().create(body=file_metadata,
fields='id').execute()

folder_id = folder_file.get('id')


# Add file to folder.
file_metadata = {
'name': 'photo.png',
'parents': [folder_id]
}
media = MediaFileUpload('photo.png',
mimetype='image/png',
resumable=True)

image_file = service.files().create(body=file_metadata,
media_body=media,
fields='id').execute()

if __name__ == '__main__':
main()

关于python - 在谷歌驱动器中创建一个文件夹并将文件上传到其中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54121952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com