2016/10/30

PyDrive Quick Overview - File Management

Here is the sample code for creating a file called "Hello.txt" on Google Drive and add "Hello World!!" as its content using PyDrive.

Create a new file on Google Drive and add its content


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from pydrive.auth import GoogleAuth

gauth = GoogleAuth()
gauth.LocalWebserverAuth() # Creates local webserver and auto handles authentication.

from pydrive.drive import GoogleDrive

# Create GoogleDrive instance with authenticated GoogleAuth instance.
drive = GoogleDrive(gauth)

# Create GoogleDriveFile instance with title 'Hello.txt'.
file1 = drive.CreateFile({'title': 'Hello.txt'})
file1.SetContentString('Hello World!!')
file1.Upload() # Upload the file.
print('title: %s, id: %s' % (file1['title'], file1['id']))
# title: Hello.txt, id: {{FILE_ID}}

The code above will create a file "Hello.txt" on Google Drive and set its content to "Hello World!!".


Double click on "Hello.txt" to open it.


Reference

File management made easy
https://googledrive.github.io/PyDrive/docs/build/html/filemanagement.html

Note, there is a mistake in the sample given in the above link for upload a new file. The code only creates a file called "Hello.txt", but it doesn't add ‘Hello World!’as its content. To add ‘Hello World!’as its content, follow the code in this post.

No comments:

Post a Comment