Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python将文件插入/上载到Google Drive API v3中的特定文件夹_Python_Google Drive Api - Fatal编程技术网

如何使用Python将文件插入/上载到Google Drive API v3中的特定文件夹

如何使用Python将文件插入/上载到Google Drive API v3中的特定文件夹,python,google-drive-api,Python,Google Drive Api,每天我下载许多pdf文件,这些文件存储在本地电脑上。要存储所有这些文件,我需要每天在Google drive上创建一个文件夹,并将所有pdf文件存储在当前日期文件夹下。 我在这里面临的挑战是,我已经成功地用Python编写了使用GDrive API v3创建文件夹的代码,但仍然坚持将所有文件上载到刚刚创建的文件夹中。以下是我如何在当前日期创建文件夹的编码: import pickle import os.path, time from googleapiclient.di

每天我下载许多pdf文件,这些文件存储在本地电脑上。要存储所有这些文件,我需要每天在Google drive上创建一个文件夹,并将所有pdf文件存储在当前日期文件夹下。
我在这里面临的挑战是,我已经成功地用Python编写了使用GDrive API v3创建文件夹的代码,但仍然坚持将所有文件上载到刚刚创建的文件夹中。以下是我如何在当前日期创建文件夹的编码:

    import pickle
    import os.path, time
    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 datetime import date
    SCOPES = ['https://www.googleapis.com/auth/drive.file']
    CLIENT_SECRET_FILE = 'e:\\Python Programs\\credentials.json'

    creds = None
    if os.path.exists('token.pickle'):
      with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)
    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(CLIENT_SECRET_FILE, SCOPES)
    creds = flow.run_local_server(port=0)
    with open('token.pickle', 'wb') as token:
      pickle.dump(creds, token)

    # main folder ID under which we are going to create subfolder
    parents_ID = '19nKlHGCypKPr40f3vjaEq22kgVkS7OCE'
    # creates sub folder under main folder ID
    fldr_name = date.today().strftime('%d%b%Y')
    mimetype = 'application/vnd.google-apps.folder'
    file_metadata = {'name': fldr_name, 'parents': [parents_ID],'mimeType': mimetype}
    # with following line I could successfully create folder without any problem
    service.files().create(body=file_metadata, fields='id').execute()

    # with following lines, i tried to get the folder ID which was recently created so that I can start coding to upload pdf files onto this.  Here im stuck
    page_token = None
    response =  service.files().list(q="mimeType='application/vnd.google-apps.folder' and name = '27Apr2020' and trashed = false", spaces='drive', fields='nextPageToken, files(id, name)', pageToken=page_token).execute()
    for file in response.get('files', []):
      print(file.get('name'), file.get('id'))
    time.sleep(5)
我得到了5秒的空白屏幕,然后它消失了。请帮助我将所有文件上载到最近创建的文件夹


感谢您的上述代码,以下行已经返回了刚刚创建的文件夹的id(fields='id')

您还可以在创建文件夹时使用fields参数返回其他值(名称、父项等)

service.files().create(body=file_metadata, fields='id, name, parents').execute()
因此,如果您在下面这样的变量中捕获返回值

folder = service.files().create(body=file_metadata, fields='id').execute()
返回的值看起来像{'id':'17w2RS1H7S8no6X0oGtkieY'}

然后,您可以通过以下命令上载文件

file_metadata = {
        'name': "test.pdf", <Name of the file to be in drive>
        'parents': [folder["id"]],
        'mimeType': 'application/pdf'
    }
media = MediaFileUpload(<local path to file>, resumable=True)
file = service.files().create(body=file_metadata, media_body=media, fields='id,name').execute()

你看过谷歌文档中的例子了吗?您需要做的唯一修改是在本地目录中循环PDF并处理它们。您是否成功创建了
驱动器服务()
?换句话说,您是否从API获得访问令牌,是否允许作用域:“”?您的应用程序需要访问该作用域才能将文件上载到驱动器。请共享您尝试过的其余代码,并在发布天线之前删除Sentive信息。。谢谢你的回复。是的,我已经用完整的代码编辑了我的问题。当然,我只设置了我的作用域googleapis.com/auth/drive.file。我成功地在一个主文件夹下创建了子文件夹。Prob是在我创建之后,我想将许多pdf文件上传到通过编码创建的子文件夹中。所以我需要知道文件夹ID,以便在同一程序中继续。我找到了答案。谢谢allGreat@Salomon你可以发布你的解决方案吗?或者是什么帮助你到达那里的?
file_metadata = {
        'name': "test.pdf", <Name of the file to be in drive>
        'parents': [folder["id"]],
        'mimeType': 'application/pdf'
    }
media = MediaFileUpload(<local path to file>, resumable=True)
file = service.files().create(body=file_metadata, media_body=media, fields='id,name').execute()
from googleapiclient.http import MediaFileUpload