Search code examples
pythonicalendar

Remove subject from .ics file - python


I need ur help with calendar in .ics format. I would like to remove subject appointment (text after 'SUMMARY:') from calendar with python and save it as .ics. How can I do this? Below I insert a piece of text from my .ics file.

SEQUENCE:0
BEGIN:VALARM
ACTION:DISPLAY
TRIGGER;RELATED=START:-PT5M
DESCRIPTION:Reminder
END:VALARM
END:VEVENT
BEGIN:VEVENT
UID:f468cba2-38bf-4fb1-ace1-1c6e6a9cde91
SUMMARY:
  This is a test text. This is a test text. This is a test text. This is a te
 test text.
LOCATION:calend1\;
ORGANIZER;CN=Kalendarz1:mailto:[email protected]
DTSTART;TZID="Europe/Warsaw":20180529T123000
DTEND;TZID="Europe/Warsaw":20180529T130000
STATUS:CONFIRMED
CLASS:PUBLIC
X-MICROSOFT-CDO-INTENDEDSTATUS:BUSY
TRANSP:OPAQUE

Solution

  • Your input is not a valid ICS file (note END:VEVENT before START:VEVENT and SEQUENCE outside any object). As such, you cannot use an ICS parser. Depending on where you got this file, and whether its consumer expects ICS or this broken ICS-adjacent format, you may want to invest in fixing the file.

    To just strike the subject can simply use a regular expression though:

    import re
    
    with open('test.ics', 'r', encoding='utf-8') as icsf:
        broken_ics = icsf.read()
    
    out = re.sub(r'\nSUMMARY:(?:.*(?:\n )?)*', '', broken_ics)
    print(out)