You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python项目使用Google Calendar API仅存最后一个事件问题求助

Fix: Only Last Google Calendar Event Saves to Text File

Hey there! Let's break down why only the last event is showing up in your text file and how to fix it—this is a super common pitfall when working with file I/O in Python, especially when you're getting started. 😊

What's Causing the Problem?

The most likely culprit is how you're opening and writing to your text file. If you're using the w (write) mode inside a loop that iterates over events, each iteration will erase the file's existing content and write only the current event. By the time the loop finishes, only the last event remains.

For example, this is the kind of code that would cause the issue:

# ❌ This will overwrite the file every time
events = service.events().list(calendarId='primary').execute().get('items', [])
for event in events:
    with open('events.txt', 'w') as f:
        start = event['start'].get('dateTime', event['start'].get('date'))
        f.write(f"{start}: {event['summary']}\n")

Two Simple Fixes

This approach is more efficient and avoids accidental overwrites. We'll gather all event details into a list first, then write everything to the file in one go.

# ✅ Collect all events first, then write once
# Fetch events from Google Calendar API
events_result = service.events().list(
    calendarId='primary',
    singleEvents=True,
    orderBy='startTime',
    maxResults=50  # Adjust based on how many events you need
).execute()
events = events_result.get('items', [])

# Build a list of event strings
event_lines = []
if not events:
    event_lines.append("No upcoming events found.\n")
else:
    for event in events:
        start_time = event['start'].get('dateTime', event['start'].get('date'))
        event_line = f"{start_time} - {event['summary']}\n"
        event_lines.append(event_line)

# Write all lines to the file
with open('calendar_events.txt', 'w', encoding='utf-8') as f:
    f.writelines(event_lines)

2. Use Append Mode (a) for Loop Writes

If you prefer writing events one at a time, use the a (append) mode instead of w. This adds new content to the end of the file instead of erasing it. Just make sure to open the file outside the loop to avoid unnecessary overhead.

# ✅ Append events one by one (loop outside file open)
events = service.events().list(calendarId='primary').execute().get('items', [])

# Open file in append mode
with open('events.txt', 'a', encoding='utf-8') as f:
    if not events:
        f.write("No upcoming events found.\n")
    else:
        for event in events:
            start_time = event['start'].get('dateTime', event['start'].get('date'))
            f.write(f"{start_time} - {event['summary']}\n")

Extra Tip: Fetch All Events (Handle Pagination)

If you have more than 25 events (the default API limit), you'll need to handle pagination to get every event. Here's how to adjust the code:

# Fetch ALL events using pagination
event_lines = []
page_token = None

while True:
    events_result = service.events().list(
        calendarId='primary',
        pageToken=page_token,
        singleEvents=True,
        orderBy='startTime'
    ).execute()
    
    events = events_result.get('items', [])
    for event in events:
        start_time = event['start'].get('dateTime', event['start'].get('date'))
        event_lines.append(f"{start_time} - {event['summary']}\n")
    
    page_token = events_result.get('nextPageToken')
    if not page_token:
        break  # Exit loop when no more pages

# Write all events to file
with open('all_calendar_events.txt', 'w', encoding='utf-8') as f:
    f.writelines(event_lines)

Key Takeaways

  • Avoid using w mode inside loops—it overwrites the file every time.
  • Prefer collecting all content first then writing once for better performance.
  • Use a mode if you need to append incrementally.
  • Remember to handle API pagination if you have lots of events.

内容的提问来源于stack exchange,提问作者Jae Park

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:31:19