<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def write(self, filename, entities, sortkey=None, columns=None):
 """Write entities out to filename in csv format. Note: this doesn't write directly into a Zip archive, because this behavior is difficult to achieve with Zip archives. Use make_zip() to create a new GTFS Zip archive. """

    if os.path.exists(filename):
      raise IOError('File exists: %s'%filename)
    # Make sure we have all the entities loaded.
    if sortkey:
      entities = sorted(entities, key=lambda x:x[sortkey])
    if not columns:
      columns = set()
      for entity in entities:
        columns |= set(entity.keys())
      columns = sorted(columns)
    # Write the csv file
    with open(filename, 'wb') as f:
      writer = unicodecsv.writer(f) # , encoding='utf-8-sig'
      writer.writerow(columns)
      for entity in entities:
        writer.writerow([entity.get(column) for column in columns])