0

I am trying to create a new file and upload it to Google Drive with Python using Google API libraries. On the official tutorial I have only found how to upload an existing file or create a folder, but I cannot figure out how to create a completely new file with a content.

This is basically a function to create a directory

def CreateFolder(name,DRIVE):
    file_metadata = {
  'name' : name,
  'mimeType' : 'application/vnd.google-apps.folder'
    }
    file = DRIVE.files().create(body=file_metadata,
                            fields='id').execute()
    print('Folder ID: %s' % file.get('id'))

Is there a way to create a new file and upload it?

Thanks

1 Answer 1

1

Check the documentations - Create Files and Uploading Files, these documents tell detailed description of uploading and creating new files to Drive using the API.

Creating a file without content:

file_metadata = {
  'name' : 'Project plan',
  'mimeType' : 'application/vnd.google-apps.drive-sdk'
}
file = drive_service.files().create(body=file_metadata,
                                    fields='id').execute()
print 'File ID: %s' % file.get('id')

Creating a file with content:

file_metadata = { 'name' : 'photo.jpg' }
media = MediaFileUpload('files/photo.jpg',
                        mimetype='image/jpeg')
file = drive_service.files().create(body=file_metadata,
                                    media_body=media,
                                    fields='id').execute()
print 'File ID: %s' % file.get('id')

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.