vendredi 16 juin 2017

Format array as argument and console/write it

I'm making a tool that takes csv table as input and outputs calendar events (ics). At some point I have a strategy that either outputs content of event to console, or writes data to ics file, so the method that writes output to a file looks like this:

def append_to_ics(event, day, file_name=None):
    output_file = open(file_name, 'a')
    output_file.write('BEGIN:VEVENT\n')
    output_file.write('DTSTART;TZID={}:{}T{}00\n'.format(event.TIME_ZONE, day.strftime('%Y%m%d'), event.start_time))
    output_file.write('DTEND;TZID={}:{}T{}00\n'.format(event.TIME_ZONE, day.strftime('%Y%m%d'), event.end_time))
    output_file.write('SUMMARY:{}\n'.format(event.class_title))
    output_file.write('DESCRIPTION: Teacher: {}; Type of class: {}\n'.format(event.teacher, event.class_type))
    output_file.write('LOCATION:{}\n'.format(event.location))
    output_file.write('TRANSP:OPAQUE\n')
    output_file.write('END:VEVENT\n\n')
    output_file.close()

'event' parameter is an object that has fields with time, title, teacher etc. 'day' is a datetime object, and 'file_name' obviously is a file I'm writing to. Method that outputs data just as a console log looks exactly the same, but there's no file open/close and instead of output_file() there's print().

Question is: I want to simplify methods so that I don't have to duplicate the same code for write and console outputs but I can't wrap my head around how to pass array/tuple/?.. 'DTSTART;TZID={}:{}T{}00\n'... then somehow format every field as earlier and then send it either to a file writer of console.

What I already tried: First format an event as in method above and store everything in a table, and the just console/write everything in a for loop. But this looks like overcomplicating because I have to store a copy of event once again but as table and only then do something with it.

Aucun commentaire:

Enregistrer un commentaire