在Google云端硬盘上创建一个文件夹(如果不存在),并使用Python脚本将文件上传到该文件夹

时间:2015-06-01 23:49:04

标签: python google-api-python-client pydrive

到目前为止,我可以将文件上传到该文件夹​​(如果存在)。我无法想出一种创造方法的方法。因此,如果文件夹不存在,我的脚本就会死掉。

import sys
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gpath = '2015'
fname = 'Open Drive Replacements 06_01_2015.xls'

gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)

file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for file1 in file_list:
    if file1['title'] == gpath:
        id = file1['id']

file1 = drive.CreateFile({'title': fname, "parents":  [{"kind": "drive#fileLink","id": id}]})
file1.SetContentFile(fname)
file1.Upload()

如果它不存在,你可以帮我修改上面的代码来创建文件夹gpath吗?

2 个答案:

答案 0 :(得分:8)

基于documentation,它应该是

<!doctype html>
<html ng-app="Contacts">
<head>    
  <title>Contacts</title>
</head>
<body>
  <h1>Contacts</h1>
  <div ng-view></div>

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular-route.min.js"></script>
  <script src="js/index.js"></script>
</body>
</html>

答案 1 :(得分:-1)

上面的答案对我不起作用,这确实有效。它返回新创建的文件夹的 id

def createRemoteFolder(folderName, parentID ):



    folderlist = (drive.ListFile  ({'q': "mimeType='application/vnd.google-apps.folder' and trashed=false"}).GetList())

    titlelist =  [x['title'] for x in folderlist]
    if folderName in titlelist:
        for item in folderlist:
            if item['title']==folderName:
                return item['id']
  
    file_metadata = {
        'title': folderName,
        'mimeType': 'application/vnd.google-apps.folder',
        'parents': [{"id": parentID}]  
    }
    file0 = drive.CreateFile(file_metadata)
    file0.Upload()
    return file0['id']