Skip to content

Instantly share code, notes, and snippets.

@tomtor
Last active May 18, 2018 06:47
Show Gist options
  • Save tomtor/2a2f88856f6350da49d0a27ce910e428 to your computer and use it in GitHub Desktop.
Save tomtor/2a2f88856f6350da49d0a27ce910e428 to your computer and use it in GitHub Desktop.
Upload file to Google Drive
#!/usr/bin/python
import sys
import os
from optparse import OptionParser
from os.path import expanduser
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from pydrive.settings import LoadSettingsFile
usage= "usage: %prog [options] FILE"
parser = OptionParser(usage= usage)
parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
help="verbose status messages", default=False)
parser.add_option("-t", "--title", dest="title", metavar="DEST",
help="title", default=False)
parser.add_option("-s", "--subdir", dest="subdir", metavar="DEST",
help="subdir", default=False)
parser.add_option("-d", "--destination", dest="destination", metavar="DEST",
help="destination directory (defaults to 'Dumps')",
default="Dumps")
(options, args) = parser.parse_args()
home = expanduser("~")
cwd= os.getcwd()
home_upload= home + os.sep + ".upload.py" + os.sep
if os.path.exists(home_upload):
os.chdir(home_upload)
gauth = GoogleAuth()
#gauth.LocalWebserverAuth()
gauth.CommandLineAuth()
drive = GoogleDrive(gauth)
os.chdir(cwd)
file_list = drive.ListFile({'q': "title='" + options.destination + "'"}).GetList()
parent = drive.CreateFile({'id': file_list[0]['id']})
file1 = drive.CreateFile()
if not options.title:
title = args[0].replace(os.sep, '|')
else:
title = options.title
if options.subdir:
subdir = drive.CreateFile({'title': options.subdir, "mimeType": "application/vnd.google-apps.folder"})
subdir['parents']= [parent]
subdir.Upload()
parent = subdir
file1['title']= title
file1['parents']= [parent]
file1.SetContentFile(args[0])
if options.verbose:
print "Start upload of " + file1['title'] + " to dir '" + options.destination + ('/' + options.subdir if options.subdir else '') + "'"
file1.Upload()
if options.verbose:
print "Done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment