python连接Google文档操作步骤总结
一、python环境准备工作
1、检查python版本号,需要python版本2.6以上(一般是2.7以上)
2、pip工具提前安装好(https://pip.pypa.io/en/stable/installing/)
1) curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
2) python get-pip.py
3)更新pip指令
On Linux or macOS:
pip install -U pip
On Windows [4]:
python -m pip install -U pip
二、导入python需要连接Google的相关库,不同的python版本执行指令不一样,如果有多个python版本最好都执行下(https://developers.google.com/sheets/api/quickstart/python#troubleshooting)
python 3.X版本:
pip3 install --upgrade google-api-python-client oauth2client
python 2.X版本:
pip install --upgrade google-api-python-client oauth2client
注意:如果提示报错 a bug in httplib2,执行如下代码:
pip install --upgrade httplib2
pip3 install --upgrade httplib2
1)生成客户端ID等信息用于连接Google账户,并下载文件(创建的项目名称默认为My Product即可)
2)创建文件credentials.json(文件名最好不要随意更改)
3)pip install --upgrade google-api-python-client oauth2client
4)Create a file named quickstart.py
in your working directory and copy in the following cofrom __future__ import print_function
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
# If modifying these scopes, delete the file token.json.
SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
SAMPLE_RANGE_NAME = 'Class Data!A2:E'
def main():
"""Shows basic usage of the Sheets API.
Prints values from a sample spreadsheet.
"""
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('sheets', 'v4', http=creds.authorize(Http()))
# Call the Sheets API
SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
RANGE_NAME = 'Class Data!A2:E'
result = service.spreadsheets().values().get(spreadsheetId=SPREADSHEET_ID,
range=RANGE_NAME).execute()
values = result.get('values', [])
if not values:
print('No data found.')
else:
print('Name, Major:')
for row in values:
# Print columns A and E, which correspond to indices 0 and 4.
print('%s, %s' % (row[0], row[4]))
if __name__ == '__main__':
main()
5)执行文件后会自动跳转到Google文档链接地址需要授权,授权OK后即可python quickstart.py