Search code examples
pythonpython-2.7icalendar

How do I parse the CATEGORIES component of an iCal calendar file in Python


I'm using icalendar to parse an .ics file with Python. I have the loop to walk the events and I can read the start and end date, the summary and attendees. My problem is that I can't figure out how to read/parse the CATEGORIES entry. Here's my code

    for event in cal.walk('vevent'):

    dateStart = event.decoded('dtstart')
    dateEnd = event.decoded('dtend')
    summary = event.get('summary')
    category = event.get('categories')
    #category = event.from_ical('categories')
    organizer = event.get('organizer')
    attendeeName = event.get('attendee') #.params['cn']
    print "Start Date: {} End Date: {} Category: {} Attendee: {} Summary: {}".format(dateStart, dateEnd,category,attendeeName,summary)

In this form, I get output that looks like this:

Start Date: 2020-02-21 End Date: 2020-02-22 Category: <icalendar.prop.vCategory object at 0x7f3bfec8a810> Attendee: None Summary: Mahashivarathri

So I'm getting the vCategory object back. If I try the commented out version of getting the category variable using from_ical(), I get an error.

Traceback (most recent call last):
  File "./ical.py", line 73, in <module>
    calTest()
  File "./ical.py", line 66, in calTest
    category = event.from_ical('categories')
  File "/usr/lib/python2.7/site-packages/icalendar/cal.py", line 330, in from_ical
    name, params, vals = line.parts()
  File "/usr/lib/python2.7/site-packages/icalendar/parser.py", line 354, in parts
    % (self, exc)
ValueError: Content line could not be parsed into parts: 'categories': Invalid content line

Here's a snipped from the .ics file with the SUMMARY, which works fine and the CATEGORIES, which doesn't

SUMMARY:Leave
CATEGORIES:other

What am I doing wrong?


Solution

  • Try this:

    category = event.get('categories').to_ical()
    

    It should give you bytes, you can add .decode() for text.