更新文件内容Google Drive API

时间:2017-01-10 16:45:54

标签: python google-api google-drive-api

我一直在使用Google Drive REST API v3,但我在尝试更新文件时遇到了困难。我当前可以从驱动器获取实际文件并读取其内容(它只是一个.txt文件),但是当我尝试更新内容时它不起作用。我没有收到任何错误,但文件本身永远不会在驱动器中更改。

以下是相关代码:

def rotate_and_update(the_file, service):
    """Rotates the names of the given file and updates its content.

    Checks to ensure that the given file has the same id as the text
    file in the drive.
    """

    file_id = the_file['id']
    file_metadata = the_file['name']

    if not file_id == '0BzLN2RWpS2IJU0pTeEdMbVJtNnc':
        raise RuntimeError("ID does not match file ID.")

    try:
        # gets file content and rotates the strings
        content = service.files().get_media(fileId=file_id).execute()

        file = service.files().get(fileId=file_id).execute()

        names = content.split()
        new_content = "\n".join(names[1:] + names[:1])

        print(content + "\n\n" + new_content)

        # updates the file with the new content
        media_body = MediaFileUpload(
            new_content, mimetype="text/plain", resumable=True)

        updated_file = service.files().update(
            fileId=file_id,
            body=file,
            media_body=media_body).execute()

        return updated_file

    except IOError:
        return None

def main():
   """Uses Google Drive API to obtain a file with a list of names, rotates
   the names, and updates the file with the new content.

   Obtains credentials through google
   """
   credentials = get_credentials()
   http = credentials.authorize(httplib2.Http())
   service = discovery.build('drive', 'v3', http=http)

   results = service.files().list(
       pageSize=10,fields="nextPageToken, files(id, name)").execute()
   items = results.get('files', [])
   print(items[0])

   rotate_and_update(items[0], service)

我也有正确的凭据。请让我知道我做错了什么,谢谢!

编辑:错误代码如下

    Traceback (most recent call last):
  File "on_call_tracker.py", line 109, in <module>
    main()
  File "on_call_tracker.py", line 106, in main
    rotate_and_update(items[0], service)
  File "on_call_tracker.py", line 78, in rotate_and_update
    new_content, mimetype="text/plain", resumable=True)
  File "C:\Python27\lib\site-packages\oauth2client\_helpers.py", line 133, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Python27\lib\site-packages\googleapiclient\http.py", line 545, in __init__
    fd = open(self._filename, 'rb')
IOError: [Errno 22] invalid mode ('rb') or filename: 'Mac\nDennis\nDee\nFrank\nWaitress\nArtemis\nCricket\nCountry\nMac\nCharlie'`enter code here`

1 个答案:

答案 0 :(得分:0)

是的,这是可能的。您需要阅读https://developers.google.com/api-client-library/python/guide/media_upload#extending-mediaupload以了解如何创建一个采用动态内容而不是文件名的子类。