Python将输出保存为文本文件

时间:2018-04-17 20:44:13

标签: python string api text google-calendar-api

我正在将Python用于学校项目,我想使用Google Calendar API。我只是按照谷歌的指南,我添加了最后一点尝试将输出保存到文本文件,但是,我遇到的问题是它只保存最后一个事件。我对Python不是很有经验,所以任何解释为什么以及如何让它做我想做的事情都会超级有用!

谢谢!

"""
    Shows basic usage of the Google Calendar API. Creates a Google Calendar API
    service object and outputs a list of the next 10 events on the user's calendar.
    """

from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import datetime

# Setup the Calendar API
SCOPES = 'https://www.googleapis.com/auth/calendar.readonly'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
    creds = tools.run_flow(flow, store)
service = build('calendar', 'v3', http=creds.authorize(Http()))

# Call the Calendar API
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
print('Getting the upcoming 10 events')
events_result = service.events().list(calendarId='primary', timeMin=now,
                                      maxResults=10, singleEvents=True,
                                      orderBy='startTime').execute()
events = events_result.get('items', [])

if not events:
    print('No upcoming events found.')
for event in events:
    start = event['start'].get('dateTime', event['start'].get('date'))

print(start, event['summary'])

outFile = open('sample.txt' , 'w')
outFile.write((start))
outFile.write( str(event['summary']))
outFile.close()

2 个答案:

答案 0 :(得分:0)

你可能需要这样的东西:

outFile = open('sample.txt' , 'w')
for event in events:
    start = event['start'].get('dateTime', event['start'].get('date'))
    print(start, event['summary'])    
    outFile.write((start))
    outFile.write(str(event['summary']))
outFile.close()

答案 1 :(得分:0)

你的缩进是错误的。

您只保存一个值并编写它。

应该如下:

outFile = open('sample.txt' , 'w')
for event in events:
    start = event['start'].get('dateTime', event['start'].get('date'))

    print(start, event['summary'])


    outFile.write((start))
    outFile.write( str(event['summary']))
    outFile.write('\n')
outFile.close()