-
Notifications
You must be signed in to change notification settings - Fork 23
/
example.py
88 lines (55 loc) · 2.44 KB
/
example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <markdowncell>
# Import basic Python libraries for use in your program: [os.path](http://docs.python.org/2/library/os.path.html) and [ConfigParser](http://docs.python.org/2/library/configparser.html)
# <codecell>
import os.path
import ConfigParser
# <markdowncell>
# An example of reading data from a Google Spreadsheet using the gspread library: http://stackoverflow.com/a/18296318/462302
#
# First you'll need to install the gspread library on your virtual machine using: `sudo pip install gspread`
# <codecell>
import gspread
# <markdowncell>
# Define `take(n, iterable)` which is a convenience function to limit the amount of output that you print. Useful when you have lots of data that will clutter up your screen!
# <codecell>
from itertools import islice
def take(n, iterable):
"Return first n items of the iterable as a list"
return list(islice(iterable, n))
# <markdowncell>
# Read the username and password from the `[google]` section of the `stat157.cfg` config file from your virtual machine home directory.
# <codecell>
home = os.path.expanduser("~")
configfile = os.path.join(home, 'stat157.cfg')
config = ConfigParser.SafeConfigParser()
config.read(configfile)
username = config.get('google', 'username')
password = config.get('google', 'password')
print username
# <markdowncell>
# Read the docid of the Google Spreadsheet from the config file.
# <codecell>
docid = config.get('questionnaire', 'docid')
client = gspread.login(username, password)
spreadsheet = client.open_by_key(docid)
worksheet = spreadsheet.get_worksheet(0)
print docid
# <markdowncell>
# Add field names to this list to include the column from the Google Spreadsheet in the filtered data output. You should choose one other column in addition to the learning style column. Refer to README.md from the homework assignment.
# <codecell>
fieldnames = ['Timestamp','What is your learning style?']
print fieldnames
# <markdowncell>
# Read in ALL rows of data from the Google Spreadsheet, but filter out columns that are not listed in `fieldnames`.
# <codecell>
filtered_data = []
for row in worksheet.get_all_records():
filtered_data.append({k:v for k,v in row.iteritems() if k in fieldnames})
print "Number of rows: {}".format(len(filtered_data))
# <markdowncell>
# Use the convenience function `take()` to print out only 3 lines from the filtered_data.
# <codecell>
for row in take(3, filtered_data):
print row